How to play a sound file?

I found here a solution for playing an audio file in WPF, which I extracted into a method, and calling this method with another method. But when a symbol PlaySound()is called sound, it is not reproduced. Does anyone have an idea why this is happening? Sound files are also marked as content, but changing the type of the resource also did not solve the problem?

My sound reproduction method:

private void PlaySound()
{
     Uri uri = new Uri(@"pack://application:,,,/Sounds/jabSound.wav");
     var player = new MediaPlayer();
     player.Open(uri);
     player.Play();
}

Then I call the method in this way, but it doesn’t play the sound file, PlaySound();

+4
source share
3 answers

You can also use SoundPlayer

SoundPlayer player = new SoundPlayer(path);
player.Load();
player.Play();

Pretty self-evident.

BONUS Here's how to do this asynchronously.

bool soundFinished = true;

if (soundFinished)
{
    soundFinished = false;
    Task.Factory.StartNew(() => { player.PlaySync(); soundFinished = true; });
} 

, , , , .

+9

, MediaPlayer , Matthew MacDonald book: Pro WPF 4.5 in C#. Chapter 26:

URI. , URI doesn’t use the application pack syntax, MediaPlayer. , MediaPlayer , WPF, , Windows Media.

:

private void PlaySound()
{
    var uri = new Uri(@"your_local_path", UriKind.RelativeOrAbsolute);
    var player = new MediaPlayer();

    player.Open(uri);
    player.Play();
}

. :

Playing embedded audio files in WPF

+10

@Anatoly MediaFailed , MediaPlayer (, - .wav ). MediaPlayer , , MediaFailed.

uri, , . bin\debug. , .wav "../../Sounds/jabSound.wav".

Uri uri = new Uri("../../Sounds/jabSound.wav", UriKind.Relative);
var player = new MediaPlayer();
player.MediaFailed += (o, args) =>
                      {
                          //here you can get hint of what causes the failure 
                          //from method parameter args 
                      };
player.Open(uri);
player.Play();
+6

Source: https://habr.com/ru/post/1534129/


All Articles