96 lines
2.8 KiB
C#
96 lines
2.8 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.Windows;
|
|
using System.Windows.Media;
|
|
|
|
namespace Wpf_AiSportsMicrospace.Common
|
|
{
|
|
public static class Utils
|
|
{
|
|
public static MediaPlayer _bgPlayer;
|
|
|
|
public static void PlayBackgroundMusic(string musicFileName, bool loop)
|
|
{
|
|
string projectRoot = Path.Combine(AppContext.BaseDirectory, @"..\..\..");
|
|
string musicPath = Path.Combine(projectRoot, "Resources", "Music", musicFileName);
|
|
|
|
if (_bgPlayer == null)
|
|
{
|
|
_bgPlayer = new MediaPlayer();
|
|
_bgPlayer.Volume = 0.5;
|
|
_bgPlayer.MediaOpened += BgPlayer_MediaOpened;
|
|
}
|
|
else
|
|
{
|
|
_bgPlayer.Stop();
|
|
}
|
|
|
|
_bgPlayer.Open(new Uri(musicPath, UriKind.Absolute));
|
|
_bgPlayer.Play();
|
|
|
|
if (loop)
|
|
{
|
|
_bgPlayer.MediaEnded -= BgPlayer_MediaEnded;
|
|
_bgPlayer.MediaEnded += BgPlayer_MediaEnded;
|
|
}
|
|
else
|
|
{
|
|
_bgPlayer.MediaEnded -= BgPlayer_MediaEnded;
|
|
}
|
|
}
|
|
|
|
// 当音乐加载完毕时触发
|
|
private static void BgPlayer_MediaOpened(object sender, EventArgs e)
|
|
{
|
|
var player = sender as MediaPlayer;
|
|
if (player != null && player.NaturalDuration.HasTimeSpan)
|
|
{
|
|
TimeSpan duration = player.NaturalDuration.TimeSpan;
|
|
Console.WriteLine($"音乐总时长: {duration.TotalSeconds:F2} 秒");
|
|
}
|
|
}
|
|
|
|
private static void BgPlayer_MediaEnded(object sender, EventArgs e)
|
|
{
|
|
_bgPlayer.Position = TimeSpan.Zero;
|
|
_bgPlayer.Play();
|
|
}
|
|
|
|
public static void StopBackgroundMusic()
|
|
{
|
|
if (_bgPlayer != null)
|
|
{
|
|
_bgPlayer.Stop();
|
|
}
|
|
}
|
|
|
|
// 安全获取当前播放时间(秒)
|
|
public static double GetMusicCurrentTime()
|
|
{
|
|
double currentTime = 0;
|
|
Application.Current.Dispatcher.Invoke(() =>
|
|
{
|
|
if (_bgPlayer != null)
|
|
currentTime = _bgPlayer.Position.TotalSeconds;
|
|
});
|
|
return currentTime;
|
|
}
|
|
|
|
// 安全获取总时长(秒)
|
|
public static int GetMusicTotalDuration()
|
|
{
|
|
int total = 0;
|
|
Application.Current.Dispatcher.Invoke(() =>
|
|
{
|
|
if (_bgPlayer != null && _bgPlayer.NaturalDuration.HasTimeSpan)
|
|
total = (int)_bgPlayer.NaturalDuration.TimeSpan.TotalSeconds;
|
|
});
|
|
return total;
|
|
}
|
|
}
|
|
}
|