Вопрос

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(); 
    } 
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top