如何播放声音文件? [英] How to play a sound file?

查看:106
本文介绍了如何播放声音文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里找到了一种解决方案,可以在WPF中播放声音文件,并将其提取到一个方法中,然后在另一个方法中调用该方法.但是调用PlaySound()时,声音不会播放.是否有人对为什么会这样有任何见解?声音文件也被标记为内容,但是更改为资源类型也不能解决问题吗?

I have found a solution on here to play a sound file in WPF which I extracted into a method and call this method in another method. But the when the PlaySound() is called the sound doesn't play. Does anyone have any insight as to why this is happening? Also the sound files are marked as content, but changing to type resource didn't remedy the problem either?

我播放声音的方法:

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

然后我像这样调用方法,但是它不会播放声音文件PlaySound();

Then I call the method like this but its doesn't play the sound file, PlaySound();

推荐答案

您还可以使用

You could also use a SoundPlayer

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

非常自我解释.

奖金:这是使其异步循环的方法.

BONUS Here's how to have it loop through asynchronously.

bool soundFinished = true;

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

打开一个任务来播放声音,等待直到声音结束,然后知道声音结束并再次播放.

Opens a task to play the sound, waits until the sound is finished, then knows it is finished and plays again.

这篇关于如何播放声音文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆