我想要做的是在指定的时间内播放音乐文件,然后停止播放。但是,正在播放整个音乐文件。有任何想法吗?
我已经尝试开始一个新线程,仍然无法正常工作。
问题是 PlaySync 阻塞了线程,因此不会处理其他消息。这包括来自 Tick 事件的停止命令。您必须使用常规的 Play 函数,该函数将是异步的并创建一个新线程来播放文件。您必须根据应用程序的工作方式来处理产生的多线程情况。
我会构建类似这样的东西:它只是在编辑窗口中乱写,所以不要指望它会像那样编译。它只是为了说明这个想法。
internal class MusicPlayer
{
private const int duration = 1000;
private Queue<string> queue;
private SoundPlayer soundPlayer;
private Timer timer;
public MusicPlayer(params object[] filenames)
{
this.queue = new Queue<string>();
foreach (var filenameObject in filenames)
{
var filename = filenameObject.ToString();
if (File.Exists(filename))
{
this.queue.Enqueue(filename);
}
}
this.soundPlayer = new SoundPlayer();
this.timer = new Timer();
timer.Elapsed += new System.Timers.ElapsedEventHandler(ClockTick);
}
public event EventHandler OnDonePlaying;
public void PlayAll()
{
this.PlayNext();
}
private void PlayNext()
{
this.timer.Stop();
var filename = this.queue.Dequeue();
this.soundPlayer.SoundLocation = filename;
this.soundPlayer.Play();
this.timer.Interval = duration;
this.timer.Start();
}
private void ClockTick(object sender, EventArgs e)
{
if (queue.Count == 0 ) {
this.soundPlayer.Stop();
this.timer.Stop();
if (this.OnDonePlaying != null)
{
this.OnDonePlaying.Invoke(this, new EventArgs());
}
}
else
{
this.PlayNext();
}
}
}
try this:
ThreadPool.QueueUserWorkItem(o => {
note.Play();
Thread.Sleep(1000);
note.Stop();
});