【发布时间】:2015-04-27 20:20:04
【问题描述】:
我有一个用 C# 编写的应用程序,它可以播放小的 .wav 文件。它使用 System.Media 命名空间中的SoundPlayer 类来播放声音,使用调用SoundPlayer.PlaySync 方法的线程来播放.wav 文件。这一切都包含在一个如下所示的类中:
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 的调用上放置了跟踪点,并在其后添加了一行,这样我就可以在使用耳机收听时查看调用的时间和返回时间。很明显,声音一直播放到最后。
如何让声音可靠地停止播放?
【问题讨论】:
-
Sounds[] 定义在哪里?
-
就在我发布的代码中
-
哎呀,对不起,一定错过了