SoundPlayer won't work with a string

Okay so i'm a noob, and spent 4 hours on Google already. So i would really appreciate some help. I'm trying to play a sound with a variable (got 100+ sounds) And i have done everything in this tutorial: http://www.codeproject.com/Articles/17422/Embedding-and-Playing-WAV-Audio-Files-in-a-WinForm

This works:

System.Media.SoundPlayer soundPlayer = new System.Media.SoundPlayer (PROGRAM.Properties.Resources.audio); soundPlayer.Play();

This Doesn't work:

string file = "PROGRAM.Properties.Resources.audio";

System.Media.SoundPlayer soundPlayer = new System.Media.SoundPlayer (file); soundPlayer.Play();

ERROR: Please be sure a sound file exists at the specified location... System.Media:SoundPlayer.ValidateSoundFile(StringfileName)

How is it possible that the string doesn't work?

Upvotes: 0

Views: 2010

Answers (1)

Chris
Chris

Reputation: 5514

When you're using PROGRAM.Properties.Resources.audio in the first example, you're actually getting a reference to a stream (which gives you the embedded audio data). This is managed by the auto-generated code your .resx produces.

When you pass "PROGRAM.Properties.Resources.audio" as a string, the SoundPlayer interprets that as a file name, and then obviously can't find it.

If you want to manually get the audio stream from a resource file, try:

var stream = PROGRAM.Properties.Resources.ResourceManager.GetStream( "audio" );
var soundPlayer = new System.Media.SoundPlayer( stream );
soundPlayer.Play();

Upvotes: 1

Related Questions