Play sound through earpiece when using MediaPlayer

2019-08-28 08:27发布

I am playing voicemail recordings in my app. The way I currently have it set up, it plays the voicemail through the speakerphone. What is the best way to be able to toggle between speakerphone and earpiece. Here is how I set up my MediaPlayer:

    mediaPlayer = new MediaPlayer();
    mediaPlayer.setOnPreparedListener(this);
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    try {
        mediaPlayer.setDataSource(url);
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }
    mediaPlayer.prepareAsync();

I am building for 4.1 plus.

1条回答
Explosion°爆炸
2楼-- · 2019-08-28 08:49

You need to set audio manager mode too. and then using audiomgr.setSpeakerphoneOn(false) api you can toggle.

audiomgr = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audiomgr.setMode(AudioManager.STREAM_MUSIC);
audiomgr.setSpeakerphoneOn(false);
查看更多
登录 后发表回答