我想在用户点击时播放哔哔声
我有一个 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/