c# - MediaElement 不播放音效

标签 c# windows-phone-7 windows-phone-8 windows-phone

我想在用户点击时播放哔哔声

我有一个 beep.mp3 文件添加到项目中(不在文件夹中)。在它的属性中,我看到 Build Action 设置为 Content

和这个 MediaElement:

<MediaElement Name="beep" Source="beep.mp3" Volume="1" AutoPlay="False"/>

然后我听不到任何声音:

beep.Play();

最佳答案

我已经构建了一个简单的示例(按照您的代码),一切都应该没问题。为了确保一切正常,我将执行如下所述的一些检查:
在 XAML 中:

<Button x:Name="myButton" VerticalAlignment="Cener" Content="BEEP"/>
<MediaElement Name="beep" Source="beep.mp3" Volume="1" AutoPlay="False" MediaFailed="beep_MediaFailed" MediaOpened="beep_MediaOpened"/>

代码隐藏:

public MainPage()
{
   InitializeComponent();

   myButton.Click += (sender, e) => { beep.Play(); };
   // this below checks if your file exists 
   if (Application.GetResourceStream(new Uri("beep.mp3", UriKind.Relative)) == null)
        MessageBox.Show("File not Exists!");
}

private void beep_MediaFailed(object sender, ExceptionRoutedEventArgs e)
{
   //  Show Message when opening failed 
   MessageBox.Show("There was an error: " + e.ErrorException.Message);
}

private void beep_MediaOpened(object sender, RoutedEventArgs e)
{
   // as it's subscribed in xaml, juts after opening the App you should hear beep
   beep.Play();
   MessageBox.Show("Media opened");
}

首先 - 在 Constructor 中,我检查我的 beep.mp3 是否存在(检查我是否可以将其作为资源流获取)。如果一切正常,您应该看不到消息。一段时间后,您应该会看到其中一条消息(失败/已打开)。如果打开,那么您还应该听到 beep.mp3。
请注意,例如,如果您将 beep.Play() 放在 InitializeComponent 之后,那么您可能听不到它 - 这是因为媒体必须在播放之前打开(当然通常不需要订阅该事件如果您不需要,但如果您遇到问题,那么很高兴知道媒体是否已打开)。

另一方面,我可能会遵循 WiredPraire 的建议(在评论中)并使用 SoundEffect 播放短声音。

希望这会有所帮助。

关于c# - MediaElement 不播放音效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21506339/

相关文章:

c# - WP7 上的 Linq to SQL Select 性能非常慢

c# - 不使用 System.Net.Sockets 时出现套接字错误

c# - MVVM:精简 ViewModel 和丰富模型

c# - Windows Phone 的 Json 序列化

c# - 添加点到 Canvas

windows-phone-8 - Windows Phone 8 试用期到期时间

c# - 在C#中发送cmd命令并读取结果

c# - 向安装添加应用程序启动选项(复选框)

windows-phone-7 - 用于 Windows Phone 开发的 FFmpeg

c# - Unity 5 Windows Phone 8 游戏在 wp8 设备中启动时崩溃