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

给你一囗甜甜゛ 提交于 2019-11-26 20:23:58

问题


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 plugged in.

AudioManager audioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);

        audioManager.setMode(AudioManager.STREAM_MUSIC);
        audioManager.setSpeakerphoneOn(true);

        if(! Globals.mediaPlayer.isPlaying()){
            Globals.mediaPlayer.start();
        }

The above code plays audio in the following ways: 1. Very few times, it plays perfectly. 2. Most of the times, it plays with a looping sound in the background. 3. Few times, it doesnot play anything.

It seems that system sounds play with no error when headset is plugged in. For example - setting the ringtone plays the corresponding ringtone correctly without any glitches. Please help me to understand how I can play a sound correctly through speaker with headset plugged in.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/31397934/how-to-play-audio-through-speaker-even-when-headset-is-plugged-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!