Use AudioTrack with AudioManager setSpeakerphoneOn

I use AudioTrack to play the sound that I get through UDP sockets. I get a lot of noise with the sound, so I decided to use AudioManager. But AudioManager changes the sound routing outside the application. Below is the code I'm using.

m_amAudioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); m_amAudioManager.setMode(AudioManager.MODE_IN_CALL); m_amAudioManager.setSpeakerphoneOn(false); 

The problem with this code is that when I close the application and start the music player, the sound comes from the front speaker, and not from the rear speaker, and I can not change it in any way. To solve this problem, I decided to add the following line when I close the application.

  m_amAudioManager.setSpeakerphoneOn(true); 

But with this line, the problem is that when I receive a call (regular call), by default the speaker turns on. I really need help with this, please.

+7
source share
2 answers

First you need to declare the permission of the user MODIFY_AUDIO_SETTINGS in your manifest in order to change the settings of the AudioManager.

 <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> 
  • Before changing any settings, you must save the current settings of AudioManager!

     oldAudioMode = audioManager.getMode(); oldRingerMode = audioManager.getRingerMode(); isSpeakerPhoneOn = audioManager.isSpeakerphoneOn(); 
  • Apply sound settings (example)

     audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT); audioManager.setMode(AudioManager.MODE_NORMAL); audioManager.setSpeakerphoneOn(true); 
  • Then, at the end, restore the settings

     audioManager.setSpeakerphoneOn(isSpeakerPhoneOn); audioManager.setMode(oldAudioMode); audioManager.setRingerMode(oldRingerMode); 
+12
source

Install this when closing the application.

m_amAudioManager.setMode (AudioManager.MODE_NORMAL);

+1
source

All Articles