Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...