【问题标题】:MediaElement doesn't play sound effectMediaElement 不播放音效
【发布时间】:2014-02-03 01:16:43
【问题描述】:

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

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

还有这个 MediaElement:

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

然后我就听不到任何声音了:

beep.Play();

【问题讨论】:

  • 可能是太短了你听不见?尝试使用更长的 mp3 以确保..
  • 我建议您考虑改用 SoundEffect 类 (reference)。音频文件必须是 WAV 文件。

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


【解决方案1】:

我已经构建了一个简单的示例(按照您的代码),一切都应该没问题。为了确保一切正常,我将执行如下所述的一些检查:
在 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");
}

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

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

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    在 Silverlight 项目中有类似的东西。尝试将其添加到 Assets 文件夹中,设置为 Content/Resource 并始终复制到输出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多