c# - 正确结束SoundEffectInstance

标签 c# .net audio xna xna-4.0

我要做的是使用内容管理器在XNA中对声音效果进行Load()编码,并自动创建一个实例来控制播放。当不再需要声音时,我想知道如何从内存中正确Unload()它?

此外,我想知道是否甚至需要Unload()。当我两次调用Load()时,第二个调用是否正确释放了第一个调用的内存?我猜想C#垃圾收集器会自动处置旧的效果和实例,因为它们已被第二个调用覆盖。它是否正确?

这些是我的自定义MySoundEffect类中的参数:

// Has sound effect been loaded?
bool loaded;

// Store our SoundEffect resource
SoundEffect effect;

// Instance of our SoundEffect to control playback
SoundEffectInstance instance;

此方法正在加载声音。
public void Load(String location)
{
    effect = Content.Load<SoundEffect>(location);

    if (effect != null) loaded = true;
    else
    {
        Error.Happened("Loading of sound effect " + location + " failed.");
        return;
    }

    // Create instance
    instance = effect.CreateInstance();
}

当不再需要声音时调用此方法:
public void Unload()
{
    loaded = false;

    instance.Dispose();

    effect.Dispose();
}

最佳答案

如果要卸载单个声音,则可以调用Dispose方法,但是重要的是,您不再需要它,否则您将获得处置元素的优惠。
您可以创建第二个ContentManager,在其中可以加载仅使用一次的声音,然后对其进行Unload

要回答第二个问题,您错了:

Each instance of ContentManager will only load any given resource once. The second time you ask for a resource, it will return the same instance that it returned last time.

To do this, ContentManager maintains a list of all the content it has loaded internally. This list prevents the garbage collector from cleaning up those resources - even if you are not using them.

关于c# - 正确结束SoundEffectInstance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19726892/

相关文章:

java - 如何使用 Java 运行文件?

iphone - ccTouchMoved 反复触发声音 & ccTouchEnded 不起作用

c# - LINQ-to-XML:选择特定节点值

c# - 如何在 .net 中获取当前语言环境的默认小数点/千位分隔符

c# - BLL与DAL之间的通信

jquery 显示不工作;可见 ="false "不工作

windows audio waveOut SetVolume 交叉连接 midi Out SetVolume

c# - DataTable RowChanged 如何获取上一行的值?

c# - 对象重置方法或事件订阅者的新引用?

.net - 1.2GB内存异常