Android play audio file during phone call

Mihir Shah picture Mihir Shah · Jan 22, 2015 · Viewed 12k times · Source

For my Android app, I want to play an audio file after answering the call from my application. App will initiate phone call and once receiver pick up the call, app should start playing recorded audio file.

By searching a lot in Google I found that this is not directly possible for unrooted device.

But any alternative of this or any other way to achieve this?

I want to implement this because functionality of the app is: if App user is in trouble, he can just press help button in the app and then app starts calling to the mentioned contact person and should play recorded audio file as soon as person received the call.

Answer

KomalG picture KomalG · Jan 22, 2015

Read the steps:

1.Some of the native music players in android device where handling this,they restrict the music when call is in TelephonyManager.EXTRA_STATE_OFFHOOK (OFFHOOK STATE) so there is no way of playing the background music using native players.But in some of the third party apss like "poweramp music palyer" it is possible.

2.By using the MediaPlayer class also it is not possible(clearly mentioned in documentation)

3.It is possible only in one case if your developing custom music player(with out using MediaPlayer class) in that implements

AudioManager.OnAudioFocusChangeListener by using this you can get the state of the audiomanager in the below code "focusChange=AUDIOFOCUS_LOSS_TRANSIENT"(this state calls when music is playing in background any incoming call came) this state is completely in developers hand whether to play or pause the music. As according to your requriment as for question you asked if you want to play the music when call is in OFFHOOK STATE dont pause playing music in OFFHOOK STATE .And this is only possible when headset is disabled

AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);

OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
    public void onAudioFocusChange(int focusChange) {
        if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT
            // Pause playback (during incoming call) 
        } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
            // Resume playback (incoming call ends)
        } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
            am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
            am.abandonAudioFocus(afChangeListener);
            // Stop playback (when any other app playing music  in that situation current app stop the audio)
        }
    }
};