前言
/Resources/count_down.mp3
属性
页面中
代码语言:javascript复制<MediaElement
x:Name="MediaAudio"
Width="0"
LoadedBehavior="Manual"
MediaEnded="MediaAudio_MediaEnded"
MediaOpened="MediaAudio_MediaOpened"
Stretch="Fill"
Visibility="Hidden"
Volume="1" />
方法
代码语言:javascript复制#region 音频播放
/// <summary>
/// 音频播放 同步进度条和视频进度
/// </summary>
/// <param name="sender">
/// </param>
/// <param name="e">
/// </param>
private void MediaAudio_MediaOpened(object sender, RoutedEventArgs e)
{
Console.WriteLine(@"播放中。。。");
}
private void MediaAudio_MediaEnded(object sender, RoutedEventArgs e)
{
MediaAudio.Stop();
MediaAudio.Position = TimeSpan.Zero;
}
#endregion 音频播放
代码
代码语言:javascript复制string mp3Path = FileToolsCommon.GetFileAbsolutePath("Resources/count_down.mp3");
MediaAudio.Source = new Uri(mp3Path);
MediaAudio.LoadedBehavior = MediaState.Manual; // 防止自动播放
MediaAudio.Position = TimeSpan.Zero;
MediaAudio.Play();
获取文件路径
代码语言:javascript复制/// <summary>
/// 获取文件的绝对路径
/// </summary>
/// <param name="path">相对路径</param>
/// <returns></returns>
public static string GetFileAbsolutePath(string path = "")
{
if (path != null)
{
string pathAll = path.Contains(":") ? path : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
pathAll = pathAll.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
return pathAll;
}
return "";
}
播放减低延迟
代码语言:javascript复制private void InitAudio()
{
string mp3Path = FileToolsCommon.GetFileAbsolutePath("Resources/count_down.mp3");
MediaAudio.Source = new Uri(mp3Path);
MediaAudio.LoadedBehavior = MediaState.Manual; // 防止自动播放
}
private void PlayCountDownAudio()
{
MediaAudio.Position = TimeSpan.Zero;
MediaAudio.Play();
}
我们可以提前初始化,并关闭它的自动播放,在需要播放的时候再播放。