同时通过2张不同的声卡播放2个音乐

问题描述 投票:19回答:2

尝试一些开箱即用的东西......我有一个简单的应用程序,带有一个按钮,当按下时,从我的Android平板电脑的音频插孔播放音乐。

public void btn1 (View view) {
    MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);
    mp.start();
}

我现在已经添加了一个usb音频接口(通过micro usb适配器),我可以听到它的声音。

我能用这个列出声卡

AudioDeviceInfo[] devices = audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS);

for (AudioDeviceInfo device : devices) {
    int b = device.getId();
    int d = device.getType();
    CharSequence productName = device.getProductName();
}

如何路由音乐以便我可以一次播放2种不同的音乐,一种通过USB播放,另一种通过耳机插孔播放?

java android audio usb soundcard
2个回答
2
投票

根据MediaPlayer文档,您可以使用接收setPreferredDevice作为参数的AudioDeviceInfo设置音频设备,请参阅https://developer.android.com/reference/android/media/MediaPlayer.html#setPreferredDevice(android.media.AudioDeviceInfo)

然后,您必须创建一个MediaPlayer才能在每个设备上播放。


2
投票

它的工作原理如下:

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

您还可以过滤耳机插头/拔下插头事件:

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

来源:me,基于MediaPlayer的SDK文档。

© www.soinside.com 2019 - 2024. All rights reserved.