Use AudioTrack with AudioManager setSpeakerphoneOn

SoH picture SoH · Jan 18, 2013 · Viewed 10.2k times · Source

I am using AudioTrack to play the sound I recieve through UDP sockets. I am getting a lot of noise along with the sound so I decided to use AudioManager. But AudioManager changes sound routing beyond the bounds of the application. Below is the code I am 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 app and start a Music Player, the sound comes from the front speaker and not the ususal back speaker and I cannot change it somehow. To resolve this issue I decided to add the following line when I am closing my app.

 m_amAudioManager.setSpeakerphoneOn(true);

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

Answer

TouchBoarder picture TouchBoarder · Jan 18, 2013

First you will need to declare the User permission MODIFY_AUDIO_SETTINGS in you manifest to change the AudioManager settings.

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

    oldAudioMode = audioManager.getMode();
    oldRingerMode = audioManager.getRingerMode();
    isSpeakerPhoneOn = audioManager.isSpeakerphoneOn();
    
  2. Apply your Audio settings (Example)

    audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
    audioManager.setMode(AudioManager.MODE_NORMAL);
    audioManager.setSpeakerphoneOn(true);
    
  3. Then on finish, restore the settings

    audioManager.setSpeakerphoneOn(isSpeakerPhoneOn);
    audioManager.setMode(oldAudioMode);
    audioManager.setRingerMode(oldRingerMode);