我在尝试在WPF应用程序中播放声音时遇到问题。当我从实际文件位置引用声音时,就像这样,

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

它工作正常。但是,我最近将相同的声音导入了我的项目,当我尝试这样做时,
private void playSound()
    {
        //location imported in the project
        SoundPlayer myNewSound = new SoundPlayer(@"pack://application:,,,/sound.wav");
        myNewSound.Load();
        myNewSound.Play();
    }

它会产生错误,并且声音不会播放。如何播放导入到项目中的声音文件?

最佳答案

您将pack Uri用作参数,但它需要Streamfilepath

将文件添加到项目后,请更改其Build Action to ContentCopy To Output Directory to Always

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

10-05 23:14