我试图让多个音频文件同时播放,所以我决定使用线程来触发它们(否则只能开始播放直到前一个完成)。
我就是这样做的。
声音是 SoundPlayers 的列表
for (int i = 0; i < sometimes; i++)
{
SoundPlayer sp = sounds[i];
Thread thread = new Thread(() =>
{
sp.PlayLooping();
});
threads.Add(thread);
}
foreach (Thread thread in threads)
{
thread.Start();
}
然后我使用计时器在 1 秒后停止所有音频文件。
foreach(Thread t in threads)
{
kill_thread(t);
MessageBox.Show(t.IsAlive.ToString());
}
[SecurityPermissionAttribute(SecurityAction.Demand, ControlThread = true)]
private void kill_thread(Thread t)
{
t.Abort();
}
我从 here 获得 kill_thread 方法.
随着消息从消息框弹出,目标线程已经以这种方式被杀死。然而,音乐还在继续播放。
有什么方法可以停止音乐吗?
提前致谢!
最佳答案
你不应该杀人 任意 线程,你的或其他的。事实上,您甚至不应该创建线程。正如其他人所说,如果您必须结束一个线程,请优雅地结束它,不要通过 Abort
核对它.它会使您的进程处于未知状态。
只需调用:
soundPlayer.Stop();
MSDN:SoundPlayer.PlayLooping Method
The .wav will be played until the Stop method is called. https://msdn.microsoft.com/en-US/library/system.media.soundplayer.playlooping(v=vs.110).aspx
至于并发播放,
SoundPlayer
不是为精细的并发播放而设计的(实际上它甚至不会这样做)。您需要为此使用不同的媒体 API。也可以看看
关于c# - 停止在线程中播放音乐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48665420/