| 特性 | SoundPlayer | MediaPlayer / MediaElement |
|---|---|---|
| 基礎架構 | .NET Framework 2.0 | WPF (PresentationCore) |
| 支援格式 | 僅 .wav | MP3、WAV、WMA、MP4 等 (依系統解碼器) |
| 同時播放 | 單一實例,後播會停止前一個 | 多實例可並行 |
| 音量控制 | 無 | Volume 屬性 0~1 |
| 靜音/聲道 | 無 | IsMuted、Balance |
| 播放速度/進度 | 無 | SpeedRatio、Position、Duration |
| UI 整合 | 無視覺元素 | MediaElement 為 UIElement 可置於 XAML |
結論:**MediaElement 最適合 WPF 應用**,功能最完整且可直接寫在 XAML。
public class MediaManager : MediaElement {
private readonly ObservableCollection<string> _files = new();
private int _index = 0;
private readonly string[] _filters = { "*.mp3", "*.wav", "*.wma" };
public MediaManager() {
LoadedBehavior = MediaState.Manual;
UnloadedBehavior = MediaState.Manual;
MediaEnded += OnMediaEnded;
LoadFilesFromConfig();
}
private void LoadFilesFromConfig() {
string root = ConfigurationManager.AppSettings["MediaRoot"];
if (Directory.Exists(root)) ScanDirectory(new DirectoryInfo(root));
}
private void ScanDirectory(DirectoryInfo dir) {
foreach (var filter in _filters) {
foreach (var file in dir.GetFiles(filter)) _files.Add(file.FullName);
}
foreach (var sub in dir.GetDirectories()) ScanDirectory(sub);
}
public void PlayList() {
if (_files.Count == 0) return;
Source = new Uri(_files[_index], UriKind.Absolute);
Play();
}
private void OnMediaEnded(object sender, RoutedEventArgs e) {
_index = (_index + 1) % _files.Count; // 循環
Source = new Uri(_files[_index], UriKind.Absolute);
Play();
}
}
<Window x:Class="MediaApp.MainWindow"
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MediaApp"
Title="音樂播放器" Height="200" Width="400" Loaded="Window_Loaded">
<StackPanel>
<local:MediaManager x:Name="Player" />
<TextBlock Text="{Binding Source, ElementName=Player, StringFormat='正在播放: {0}'}" />
<Slider Maximum="{Binding NaturalDuration.TimeSpan.TotalSeconds, ElementName=Player}"
Value="{Binding Position.TotalSeconds, ElementName=Player, Mode=TwoWay}" />
</StackPanel>
</Window>
public partial class MainWindow : Window {
public MainWindow() => InitializeComponent();
private void Window_Loaded(object sender, RoutedEventArgs e) => Player.PlayList();
}
<appSettings>
<add key="MediaRoot" value="D:\Music\" />
</appSettings>
Play/Pause/Stop/Next/Previous 方法對應 UI 按鈕。INotifyPropertyChanged 暴露 CurrentTrack、Progress 供繫結。