Cannot stop AudioTrack on Android 5

时光怂恿深爱的人放手 提交于 2019-12-22 00:33:12

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/28713136/cannot-stop-audiotrack-on-android-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!