Threading issue when playing music file
-
18-03-2021 - |
سؤال
What I'm trying to do is play a music file for a specified duration, and then stop playing. However, the whole music file is being played. I cannot use the 'PlaySync()' method as I cannot have the thread being blocked.
المحلول
maybe something like this
Task.Factory.StartNew(() =>
{
var player = new SoundPlayer();
player.SoundLocation = "myfile";
player.Play();
Thread.Sleep(duration)
player.Stop();
});
نصائح أخرى
You don't have to spawn a new thread yourself, as the SoundPlayer.Play
method does it itself.
try this version:
public void Play()
{
player = new SoundPlayer();
player.SoundLocation = "myfile";
Timer timer = new Timer();
timer.Tick += (s,e) =>
{
player.Stop();
timer.Stop();
};
timer.Interval = duration;
player.Play();
timer.Start();
}
لا تنتمي إلى StackOverflow