Playing 2 musics through 2 different sound cards at same time

半世苍凉 提交于 2019-12-03 10:51:56

According to the MediaPlayer documentation, you can set the audio device using setPreferredDevice which receive an AudioDeviceInfo as a parameter, see https://developer.android.com/reference/android/media/MediaPlayer.html#setPreferredDevice(android.media.AudioDeviceInfo).

You will then have to create one MediaPlayer to play on each device.

it works about like this:

protected void playAudio() {
    this.playByDeviceIdx(0, R.raw.xxx);
    this.playByDeviceIdx(1, R.raw.yyy);
}

protected void playByDeviceIdx(int deviceIndex, @IdRes int resId) {

    /* obtain audio-output device-infos */
    deviceInfos[] devices = audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS);

    /* check, if the desired index is even within bounds */
    if(deviceInfos.length < deviceIndex) {

        /* create an instance of MediaPlayer */
        MediaPlayer mp = MediaPlayer.create(this, resId);

        /* assign a preferred device to the MediaPlayer instance */
        mp.setPreferredDevice(deviceInfos[deviceIndex]);

       /* start the playback (only if a device exists at the index) */
       mp.start();
    }
}

you could also filter for the headset jack plug/unplug event:

IntentFilter intentFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
Intent intent = context.registerReceiver(null, intentFilter);
boolean isConnected = intent.getIntExtra("state", 0) == 1;

sources: me, based upon the SDK documentation for the MediaPlayer.

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