WPF开发-音频播放

前言

/Resources/count_down.mp3

属性

image-20240730113950982

页面中

1
2
3
4
5
6
7
8
9
<MediaElement
x:Name="MediaAudio"
Width="0"
LoadedBehavior="Manual"
MediaEnded="MediaAudio_MediaEnded"
MediaOpened="MediaAudio_MediaOpened"
Stretch="Fill"
Visibility="Hidden"
Volume="1" />

方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#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 音频播放

代码

1
2
3
4
5
string mp3Path = FileToolsCommon.GetFileAbsolutePath("Resources/count_down.mp3");
MediaAudio.Source = new Uri(mp3Path);
MediaAudio.LoadedBehavior = MediaState.Manual; // 防止自动播放
MediaAudio.Position = TimeSpan.Zero;
MediaAudio.Play();

获取文件路径

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/// <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 "";
}

播放减低延迟

1
2
3
4
5
6
7
8
9
10
11
12
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();
}

我们可以提前初始化,并关闭它的自动播放,在需要播放的时候再播放。