1

Playing sound over speakers while playing music through headphones

This guy had exactly the same problem to solve as I do now. I read all of his responses and since some were outdated and some didn't work at all or not on most devices then I decided that maybe it is better approach to go with quick switching. Also I was unable to contact him directly.

I need to play continuous tone on headphones to power my peripheral and sometimes (~3-4 times a second would be very good) play a very short, but still audible "beep" over speakers. It is crucial that headphones are interrupted for as short time as possible or not at all.

This is how I am doing it at the moment: I have one main continuous AudioTrack for power and one for the "beep". It works like i want it to, but the switch between 2 tracks is very slow - up to 600ms on my phone and about 200ms on my friends' phones. This is too much if i want to play the beeps more than 2 times a second. If I timed the commands, then the one taking all the time was beepTrack.play().

powerThread = new Thread(new Runnable() {
        @Override
        public void run() {
            while(running) {
                if (systemAudioManager.isWiredHeadsetOn()) {
                    powerTrack.write(powerSamples, 0, powerSamples.length);
                }

            }
        }
    });

private void playBeep() {
    beepTrack = new AudioTrack(
            BEEP_STREAM_TYPE,
            BEEP_SAMPLE_RATE,
            AudioFormat.CHANNEL_OUT_MONO,
            AudioFormat.ENCODING_PCM_16BIT,
            minBeepBufferSize,
            AudioTrack.MODE_STREAM
    );

    beepTrack.setStereoVolume(AudioTrack.getMaxVolume() / 2, AudioTrack.getMaxVolume() / 2);
    powerTrack.stop();

    //Delay, otherwise my power track isn't stopped and starts sounding over speakers
    try {
        Thread.sleep(50);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    //Main time consumer
    beepTrack.play();
    beepTrack.write(beepSamples, 0, beepSamples.length / 2);

    beepTrack.stop();
    powerTrack.play();
}
Community
  • 1
  • 1

0 Answers0