Search code examples
androidandroid-5.0-lollipopaudiotrack

Cannot stop AudioTrack on Android 5


I cannot stop playback of an AudioTrack on a Nexus 4 running Android 5.0.1. Am I doing something wrong?

The code is very simple (it's actually just a test app) and it works perfectly on devices running 2.3.6 and 4.4. Here's the relevant portion:

mPlugReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if(Intent.ACTION_HEADSET_PLUG.equals(intent.getAction())) {
            boolean plugged = intent.getIntExtra("state", 0) == 1;
            if(plugged) {
                log.debug("audio device plugged");
                boolean mic = intent.getIntExtra("microphone", 0) == 1;
                if(mic) {
                    log.debug("microphone detected");
                    mPowerTone.play();
                }
            }
        }
        else if(AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) {
            log.debug("stopping power tone");
            mPowerTone.pause();
            mPowerTone.flush();
            mPowerTone.stop();
        }               
    }           
};

On 5.0.1, it logs "stopping power tone" but the track continues to play! It even continues to play after I exit the app. Sometimes it stops after a few seconds, and sometimes I have to force close the app.

I tried both with and without the calls to pause() and flush(), to no avail. It works without those calls on the older devices.


Solution

  • This unanswered question led me to a solution. If you call AudioTrack#stop() on Lollipop, even in conjunction with the methods that actually work, playback will not stop! You must use a condition like this:

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mPowerTone.pause();
        mPowerTone.flush();                     
    }
    else {
        mPowerTone.stop();
    }
    

    Keep up the good work, Google.