即使插入耳机,如何通过扬声器播放音频? [英] 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();
}
上面的代码以下列方式播放音频: 1.很少能完美播放. 2.大多数情况下,它在背景中播放循环声音. 3.几次,它什么都不玩.
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.
推荐答案
稍作研究(可能还不止于此),我想出了解决方案.
After working on it a little bit(maybe more than that), I figured out the solution for it.
我们应该创建自己的MediaPlayer实例并为该实例设置Audio流类型,而不是更改AudioManager的设置.我们可以将其设置为STREAM_RING,以将音频路由到耳机和扬声器.
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();}
然后,您可以收听onPreparedListener来启动音频.请查看博客通过Android中的扬声器路由音频以获得更好的图片.
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.
这篇关于即使插入耳机,如何通过扬声器播放音频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!