Play sound through earpiece when using MediaPlayer

2019-08-28 08:10发布

问题:

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:

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);