[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Play an audio resource in C#

[Play an audio resource in C#]

The System.Media.SoundPlayer class lets you easily play a WAV file stored as an audio resource. For this example, first add the WAV file as an audio resource. To do that, open the Project menu and select Properties. Then open the Add Resource dropdown and select Add Existing File. Select the WAV file and click Open.

This example has image files with the same names as sound files. For example, Dog.png and Dog.wav. When you create an audio resource, Visual Studio gives it a name to differentiate it from the other file as in Dog1. I renamed the resources as in DogSound so make the name more self-documenting.

After you create an audio resource, the program can play it by using a SoundPlayer object. The following code shows the PlayWav method that the program uses to play sound resources.

// The player making the current sound. private SoundPlayer Player = null; // Dispose of the current player and // play the indicated WAV file. private void PlayWav(Stream stream, bool play_looping) { // Stop the player if it is running. if (Player != null) { Player.Stop(); Player.Dispose(); Player = null; } // If we have no stream, we're done. if (stream == null) return; // Make the new player for the WAV stream. Player = new SoundPlayer(stream); // Play. if (play_looping) Player.PlayLooping(); else Player.Play(); }

The method first checks whether the Player object exists and, if it does, disposes of that object.

It then creates a SoundPlayer, passing its constructor the stream representing the audio resource. The method then calls the object's Play or PlayLooping method to play the sound.

The following code shows how the example plays the ChicksSound resource when you check the chicks radio button.

private void radChicks_Click(object sender, EventArgs e) { PlayWav(Properties.Resources.ChicksSound, true); }

Note that the SoundPlayer class cannot play multiple WAV files at the same time, even if you use multiple SoundPlayer objects. That means if you use the SoundPlayer to play a WAV file, the player automatically stops any WAV files that it is currently playing.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.