Playing 2 musics through 2 different sound cards at same time

Playing 2 musics through 2 different sound cards at same time



Trying something pretty out of the box... I have a simple app with a button that when pushed, plays music out of the audio jack of my android tablet.


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



I've now added a usb audio interface (through a micro usb adapter) and I can hear audio out of it.



I'm able to list the sound cards with this


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

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



How do I route music so that I can play 2 different music at once, one through usb and the other through the headphone jack?




2 Answers
2



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).


MediaPlayer


setPreferredDevice


AudioDeviceInfo



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


MediaPlayer



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.



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)