How to Play audio through speaker even when headset is plugged in?

前端 未结 2 564
长情又很酷
长情又很酷 2020-12-05 14:09

The title of the question might look repeated, but my problem is a sometimes problem and causes glitches. I have used the below code to play through speaker when headset is

相关标签:
2条回答
  • I had a similar problem that I solved, creating a new media player if it's not playing and setting the media player stream type to the same mode of the audio manager, try with something like this:

    AudioManager audioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
    audioManager.setMode(AudioManager.STREAM_MUSIC);
    audioManager.setSpeakerphoneOn(true);
    
    if(! Globals.mediaPlayer.isPlaying()){
        MediaPlayer mp = MediaPlayer.create(....);
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mp.start();
    }
    

    In my case I was using AudioManager.MODE_IN_COMMUNICATION. Also be sure to set the permission

    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    

    in the AndroidManifest.xml

    0 讨论(0)
  • 2020-12-05 15:03

    After working on it a little bit(maybe more than that), I figured out the solution for it.

    Instead of changing settings of AudioManager, we should create our own MediaPlayer instance and set the Audio stream type for that instance. We can set it to STREAM_RING to route the audio to headset and speaker.

    player.reset();
        player.setAudioStreamType(AudioManager.STREAM_RING);
        try {
            player.setDataSource(context, uri);
            player.prepareAsync();}
    

    Then, you can listen to onPreparedListener to start the audio. Please check the blog Route audio through speaker in Android to get a better picture.

    0 讨论(0)
提交回复
热议问题