How to play a WPF Sound File resource

前端 未结 3 2036
情深已故
情深已故 2020-12-01 14:46

I am trying to play a sound file in my WPF application. Currently I have the following call:

private void PlaySound(string uriPath)
{
    Uri uri = new Uri(@         


        
3条回答
  •  半阙折子戏
    2020-12-01 14:59

    You can also load a Stream into the SoundPlayer if the .wav file is an Embedded Resource. Note that in this example the resources are in a folder called Resources that is in the root of the project, that is why it is written {0}.Resources.{1}.

    //the wav filename
    string file = "emergency_alarm_002.wav";
    
    //get the current assembly
    var assembly = System.Reflection.Assembly.GetExecutingAssembly();
    
    //load the embedded resource as a stream
    var stream = assembly.GetManifestResourceStream(string.Format("{0}.Resources.{1}", assembly.GetName().Name, file));
    
    //load the stream into the player
    var player = new System.Media.SoundPlayer(stream);
    
    //play the sound
    player.Play();
    

提交回复
热议问题