简体   繁体   中英

How to play a sound that was imported into C# WPF project?

I have an issue with trying to play sound in my WPF application. When I reference the sound from its actual file location, like this,

private void playSound()
    {
        //location on the C: drive
        SoundPlayer myNewSound = new SoundPlayer(@"C:\Users\...\sound.wav");
        myNewSound.Load();
        myNewSound.Play();
    }

it works fine. However, I recently imported the same sound into my project, and when I try to do this,

private void playSound()
    {
        //location imported in the project
        SoundPlayer myNewSound = new SoundPlayer(@"pack://application:,,,/sound.wav");
        myNewSound.Load();
        myNewSound.Play();
    }

it produces an error and the sound won't play. How can I play the sound file imported into my project?

Easiest/shortest way for me is to change Build Action of added file to Resource , and then just do this:

   SoundPlayer player = new SoundPlayer(Properties.Resources.sound_file);//sound_file is name of your actual file
   player.Play();

You are using pack Uri as argument, but it needs either a Stream or a filepath .

As you have added the file to your project, so change its Build Action to Content , and Copy To Output Directory to Always .

using (FileStream stream = File.Open(@"bird.wav", FileMode.Open))
    {
        SoundPlayer myNewSound = new SoundPlayer(stream);
        myNewSound.Load();
        myNewSound.Play();
    }

You can do it with reflection.

Set the property Build Action of the file to Embedded Resource .

You can then read it with:

var assembly = Assembly.GetExcetutingAssembly();
string name = "Namespace.Sound.wav";
using (Stream stream = assembly.GetManifestResourceStream(name))
{
    SoundPlayer myNewSound = new SoundPlayer(stream);
    myNewSound.Load();
    myNewSound.Play();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM