Android在通话期间播放歌曲

时间:2014-06-20 05:44:02

标签: android call audio-player

我正在尝试构建一个在通话期间播放歌曲的应用程序。打电话给某人时工作正常。但是在继续通话的同时无法播放歌曲。 我把mp3文件放在assets文件夹中。这是我的代码:

if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
    // active
    //Log.i(LOG_TAG, "OFFHOOK");
    try {
        AssetFileDescriptor descriptor = getAssets().openFd("la.mp3");
        mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
        descriptor.close();

        mp.prepare();
        mp.setVolume(1f, 1f);
        mp.setLooping(true);
        mp.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:0)

我能够在调用callIntent -

之前调用playAudio()
public void playAudio() {
    try {
        if (m.isPlaying()) {
            Log.d("Playing the audio", "");
            m.stop();
            m.release();
            m = new MediaPlayer();
        }
        m.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
        AssetFileDescriptor descriptor = getAssets().openFd("test.mp3");
        m.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
        descriptor.close();
        m.prepare();
        m.setVolume(1f, 1f);
        m.setLooping(true);
        m.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void stopAudio() {
    if (m.isPlaying()) {
        Log.d("stop the audio", "");
        m.stop();
        m.release();
        m = new MediaPlayer();
    }

}

public class MyPhoneStateListener extends PhoneStateListener {

    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        switch (state) {
            //Hangup
            case TelephonyManager.CALL_STATE_IDLE:
                stopAudio();
                audioManager.setSpeakerphoneOn(false);
                break;
            //Outgoing
            case TelephonyManager.CALL_STATE_OFFHOOK:
                break;
            //Incoming
            case TelephonyManager.CALL_STATE_RINGING:

                break;
        }
    }
}