Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use System.Media.SoundPlayer to asynchronously play a sound file?
    primarykey
    data
    text
    <p>Here's a deceptively simple question:</p> <p><strong>What is the proper way to asynchronously play an embedded .wav resource file in Windows Forms?</strong></p> <p>Attempt #1:</p> <pre><code>var player = new SoundPlayer(); player.Stream = Resources.ResourceManager.GetStream("mySound"); player.Play(); // Note that Play is asynchronous </code></pre> <ul> <li>Good: doesn't block the UI thread</li> <li>Bad: SoundPlayer and the embedded resource stream are not immediately disposed.</li> </ul> <p>Attempt #2:</p> <pre><code>using (var audioMemory = Resources.ResourceManager.GetStream("mySound")) { using (var player = new SoundPlayer(audioMemory)) { player.Play(); } } </code></pre> <ul> <li>Good: UI thread is not blocked, SoundPlayer and audio memory stream are immediately disposed.</li> <li>Bad: Race condition! Play() is async, and if audio memory gets disposed before Play is done...boom! Runtime exception is thrown.</li> </ul> <p>Attempt #3:</p> <pre><code>using (var audioMemory = Resources.ResourceManager.GetStream("mySound")) { using (var player = new SoundPlayer(audioMemory)) { player.PlaySync(); } } </code></pre> <ul> <li>Good: Player and audio stream are immediately disposed.</li> <li>Bad: PlaySync blocks the UI thread</li> </ul> <p>Attempt #4:</p> <pre><code>ThreadPool.QueueUserWorkItem(ignoredState =&gt; { using (var audioMemory = Resources.ResourceManager.GetStream("mySound")) { using (var player = new SoundPlayer(audioMemory)) { player.PlaySync(); } } }); </code></pre> <ul> <li>Good: UI doesn't freeze, player and memory stream are immediately disposed.</li> <li>Bad: Because this fires often, we may run out of thread pool threads! See Larry Osterman's <a href="http://blogs.msdn.com/larryosterman/archive/2009/06/29/what-s-wrong-with-this-code-part-26-the-answer.aspx" rel="noreferrer">what's wrong with this code part 26</a>.</li> </ul> <p>It seems like SoundPlayer should have a PlayAsyncCompleted event. Unfortunately, no such event exists. Am I missing something? What's the proper way to asynchronously play a .wav embedded resource in Windows Forms?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload