0

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.

Dot NET
  • 4,891
  • 13
  • 55
  • 98
  • 1
    Does `player` has its own `Stop` method? – sll Dec 16 '11 at 09:33
  • Maybe your stop call comes *before* the sound has even started. Workaround would be to start your timer at the start of playback, not at the 'play' request. – jv42 Dec 16 '11 at 09:39
  • What is `PlaySync()` method and why you need this one? – sll Dec 16 '11 at 09:39
  • I can't find any details regarding this one, am I missed something? – sll Dec 16 '11 at 09:41
  • I said "I cannot use the 'PlaySync()' method as I cannot have the thread being blocked"... why do you assume I 'need' it. – Dot NET Dec 16 '11 at 09:42
  • anyway try out adding `thread.Join()` after the `thread.Start()` – sll Dec 16 '11 at 09:44

2 Answers2

2

maybe something like this

 Task.Factory.StartNew(() =>
   {
    var player = new SoundPlayer();
    player.SoundLocation = "myfile";
    player.Play();
    Thread.Sleep(duration)
    player.Stop();
   });
wiero
  • 2,176
  • 1
  • 19
  • 28
  • +1 this looks an interesting possibility, why the downvote? (I upvoted too). – jv42 Dec 16 '11 at 09:49
  • 1
    code didn't compile at first version ;) maybe that's the reason – wiero Dec 16 '11 at 09:50
  • 2
    downvoted because Thread.Sleep is never a good solution (except in very special corner case situations I have never heard about). Moreover this version uses 2 threads (1 for the player.Play() method and one spawned by StartNew), and blocks one of them uselessly – Falanwe Dec 16 '11 at 09:50
  • Anyway I suggest using `thread.Jojn()` to wait whilst "playing" thread would finish its job, basically addign `thread.Join()` after the `thread.Start()` – sll Dec 16 '11 at 09:52
  • 1
    @Falanwe thanx for your tips, i find them usefull and probably will never user Thread.Sleep again ;) – wiero Dec 16 '11 at 09:59
2

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(); 
    } 
Falanwe
  • 4,636
  • 22
  • 37