Playing 2 musics through 2 different sound cards at same time

后端 未结 2 1663
余生分开走
余生分开走 2021-02-12 19:24

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 voi         


        
2条回答
  •  不知归路
    2021-02-12 19:36

    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.

提交回复
热议问题