我有一个使用C#编写的应用程序,可以播放小的.wav文件。它使用System.Media命名空间中的SoundPlayer
类播放声音,使用调用SoundPlayer.PlaySync
方法播放.wav文件的线程。在一个类中,看起来像这样这一切都包裹起来:SoundPlayer.Stop不会停止声音播放
public class SoundController {
private object soundLocker = new object();
protected Thread SoundThread { get; set; }
protected string NextSound { get; set; }
protected AutoResetEvent PlayASoundPlag { get; set; }
protected Dictionary<string, SoundPlayer> Sounds { get; set; }
protected bool Stopping { get; set; }
public string SoundPlaying { get; private set; }
public SoundController() {
PendingCount = 0;
PlayASoundFlag = new AutoResetEvent(false);
Sounds = new Dictionary<string, SoundPlayer>();
soundLocker = new object();
Stopping = false;
SoundThread = new Thread(new ThreadStart(SoundPlayer)) { Name = "SoundThread", IsBackground = true };
SoundThread.Start();
}
private void SoundPlayer() {
do {
PlayASoundFlag.WaitOne();
bool soundWasPlayed = false;
while (!Stopping && NextSound != null) {
lock (soundLocker) {
SoundPlaying = NextSound;
NextSound = null;
}
Sounds[ SoundPlaying ].PlaySync();
lock (soundLocker) {
SoundPlaying = null;
soundWasPlayed = true;
}
}
} while (!Stopping);
}
public bool HasSound(string key) {
return Sounds.ContainsKey(key);
}
public void PlayAlarmSound(string key, bool stopCurrentSound) {
if (!Sounds.ContainsKey(key))
throw new ArgumentException("Sound unknown", "key");
lock (soundLocker) {
NextSound = key;
if (SoundPlaying != null && stopCurrentSound)
Sounds[ SoundPlaying ].Stop();
PlayASoundFlag.Set();
}
}
}
当我的程序调用PlaySound
方法和声音正在播放时,Stop
方法被调用,但声音的播放实际上并没有停止。我在呼叫Stop
时添加了一些跟踪点,并且在我之后添加了一条线,以便我可以看到何时进行呼叫以及何时返回,同时用耳机收听。很明显,声音一直播放到最后。
如何让声音停止可靠播放?
声音[]定义在哪里? – Pseudonym
这是在我发布的代码 –
oh derp,对不起,一定是错过了 – Pseudonym