gpt4 book ai didi

android - SoundManager,如何停止声音播放

转载 作者:行者123 更新时间:2023-12-02 23:45:38 28 4
gpt4 key购买 nike

我使用简单的SoundManager播放来自sounpool的声音。我的问题是,即使我使用mySound.release();,退出应用程序时声音也不会停止播放。
否则,一切都会正常进行,这是我的代码。

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

public class SoundManager {

private Context pContext;
private SoundPool mySound;

private float rate = 1.0f;
private float masterVolume = 1.0f;
private float leftVolume = 1.0f;
private float rightVolume = 1.0f;
private float balance = 0.5f;

// Constructor, setup the audio manager and store the app context
public SoundManager(Context appContext)
{
mySound = new SoundPool(16, AudioManager.STREAM_MUSIC, 100);

pContext = appContext;
}

// Load up a sound and return the id
public int load(int sound_id)
{
return mySound.load(pContext, sound_id, 1);

}


// Play a sound
public void play(int sound_id)
{
mySound.play(sound_id, leftVolume, rightVolume, 1, 0, rate);
}

// Set volume values based on existing balance value
public void setVolume(float vol)
{
masterVolume = vol;

if(balance < 1.0f)
{
leftVolume = masterVolume;
rightVolume = masterVolume * balance;
}
else
{
rightVolume = masterVolume;
leftVolume = masterVolume * ( 2.0f - balance );
}

}


public void unloadAll()
{
mySound.release();
}

}

最佳答案

方法play()返回int StreamId。您需要将此StreamId保留在变量上并调用stop方法。例如:

声明一个Stream ID变量:

private int mStreamId;

然后,在开始新的声音流时保留它:
// Play a sound
public void play(int sound_id)
{
mStreamId = mySound.play(sound_id, leftVolume, rightVolume, 1, 0, rate);
}

因此,您可以停止它:
mySound.stop(mStreamId);

现在,您可以在 Activity 事件 onStoponPause或您想要的位置停止声音流。

编辑:

释放 SoundPool资源的最佳方法是调用 release,并在停止播放声音后将引用设置为null。例如:
@Override
protected void onPause() {
super.onPause();
mSoundManager.unloadAll();
}

SoundManager上,将 unloadAll方法更改为:
public void unloadAll()
{
mySound.release();
mySound = null;
}

Note the following:

onPause – is always called when the activity is about to go into the background.

release: releases all the resources used by the SoundPool

object null: this SoundPool object can no longer be used (like @DanXPrado said) so set it to null to help the Garbage Collector identify it as reclaimable.



有关更多详细信息,请参见 this tutorial about SoundPool

希望这可以帮助。

关于android - SoundManager,如何停止声音播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31971198/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com