Android - Play audio from earpiece

后端 未结 7 1965
旧巷少年郎
旧巷少年郎 2020-12-02 08:27

I\'d like to play audio from a file into the phone\'s earpiece (or headset of that is connected) using the android MediaPlayer. I tried using the MODE_IN_CALL h

相关标签:
7条回答
  • 2020-12-02 09:19

    The following code works fine for me and I have tested in on multiple devices:

    1- creating instances:

    MediaPlayer mPlayer = MediaPlayer.create(MainActivity.this, R.raw.skype_call_dialing);
    AudioManager mAudioManager = ((AudioManager).getSystemService(Context.AUDIO_SERVICE));
    

    2- if you want to set volume to max (optional)

     int maxVolumeMusic = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
     mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolumeMusic, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
     mAudioManager.setMode(AudioManager.STREAM_MUSIC);
    

    3- set audio to play from earpiece:

    mAudioManager.setSpeakerphoneOn(false);
    

    4- play:

    mPlayer.setLooping(true);
    mPlayer.start();
    

    Done!!!! But there is some tips I am going to share with you:

    1- in step 2, if you set Audiomanager.setMode() before AudioManager.setStreamVolume() then the volume would not set to max!

    2- if you add mPlayer.prepare() before mPlayer.setLooping(true); it would lead to crash!, you should not use mPlayer.prepare() while mPlayer is initializing like this:

    MediaPlayer mPlayer = MediaPlayer.create(MainActivity.this, R.raw.skype_call_dialing);
    

    3- in step 2, mAudioManager.setMode() I used AudioManager.STREAM_MUSIC, when I try other modes, in many cases I was not able to switch on and off speaker!

    0 讨论(0)
提交回复
热议问题