Android play audio file during phone call

*爱你&永不变心* 提交于 2019-12-20 20:38:42

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/28082471/android-play-audio-file-during-phone-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!