通过插入耳机的扬声器播放音频

时间:2017-03-10 18:04:12

标签: android audio android-mediaplayer

我想通过带插入式耳机的扬声器播放音频文件。

我尝试了以下内容: MainActivity.java:

AudioManager audioManager = (AudioManager)mainActivity
     .getSystemService(Context.AUDIO_SERVICE);
audioManager.setMode(AudioManager.STREAM_MUSIC);
audioManager.setSpeakerphoneOn(true);
MediaPlayer mp = MediaPlayer.create(mainActivity, R.raw.chime);
mp.setAudioStreamType(AudioManager.STREAM_RING);
mp.start();

清单:

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

但音频仍然通过插入的耳机播放。如何正确插入耳机,将音频输出定向到扬声器?

编辑1:

我尝试了帖子Android, how to route the audio to speakers when headphones inserted?中的以下代码:

   MediaPlayer mp = MediaPlayer.create(mainActivity, R.raw.chime);
   AudioManager am = (AudioManager) mainActivity.getSystemService(mainActivity.AUDIO_SERVICE);
    try {
        mp.setAudioStreamType(AudioManager.STREAM_ALARM);
        mp.setLooping(true);
        mp.prepare();
    } catch (IllegalArgumentException | SecurityException| IllegalStateException | IOException e) {
        Log.i("TAG","Error is " + e.toString());
        e.printStackTrace();
    }
    am.requestAudioFocus(null, AudioManager.STREAM_ALARM,AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
    mp.start();

但我得到了

  

java.lang.IllegalStateException

任何想法如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

我将提供一个完整的代码段(在Android 24上测试),我必须从多个提示汇总到解决方案:

public class AudioClass
{
    AudioManager audioManager;
    Activity activity;

    public AudioClass(Activity activity)
    {
       this.activity = activity;

        //NEEDS TO BE DONE BEFORE PLAYING AUDIO!
        audioManager = (AudioManager)
            activity.getSystemService(Context.AUDIO_SERVICE);
        audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
        audioManager.setSpeakerphoneOn(true);
    }

    public void playAudio() {
        //CAN BE CALLED FROM ANYWHERE AFTER AudioClass IS INSTANTIATED
        MediaPlayer mp = MediaPlayer.create(activity, R.raw.audio_file_name);
        mp.setAudioStreamType(AudioManager.MODE_IN_COMMUNICATION);
        mp.start();
    }
}

需要在清单中设置修改音频设置的权限:

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