MediaElement无法播放音效。

4

当用户点击时,我希望播放蜂鸣声音效果。

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

并且有这个MediaElement

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

接下来我就听不到任何声音了:

beep.Play();

也许只是因为它太短了,所以你听不到吗?尝试使用更长的MP3文件来确认一下。 - har07
1
我建议您考虑使用 SoundEffect 类替代(参考)。但是,音频文件必须是 WAV 格式的。 - WiredPrairie
2个回答

0

我已经按照您的代码构建了一个简单的示例,一切应该都没问题。为了确保一切都正常,我将执行以下描述的一些检查:
在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的声音。
请注意,如果您例如在InitializeComponent之后立即放置beep.Play(),则可能无法听到它-这是因为媒体必须在播放之前打开(当然,如果您不需要订阅该事件,则通常没有必要,但如果您遇到问题,则知道媒体是否已打开很好)。

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

希望这能有所帮助。


0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接