首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

WPF 實作音訊檔案循環順序播放完整方案

     編輯:ASP.NET 基礎

WPF 音訊播放類別比較

特性SoundPlayerMediaPlayer / MediaElement
基礎架構.NET Framework 2.0WPF (PresentationCore)
支援格式僅 .wavMP3、WAV、WMA、MP4 等 (依系統解碼器)
同時播放單一實例,後播會停止前一個多實例可並行
音量控制無Volume 屬性 0~1
靜音/聲道無IsMuted、Balance
播放速度/進度無SpeedRatio、Position、Duration
UI 整合無視覺元素MediaElement 為 UIElement 可置於 XAML

結論:**MediaElement 最適合 WPF 應用**,功能最完整且可直接寫在 XAML。

架構設計:繼承 MediaElement 封裝播放清單邏輯

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();
    }
}

XAML 使用

<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>

Code-Behind

public partial class MainWindow : Window {
    public MainWindow() => InitializeComponent();
    private void Window_Loaded(object sender, RoutedEventArgs e) => Player.PlayList();
}

App.config 設定媒體庫根目錄

<appSettings>
  <add key="MediaRoot" value="D:\Music\" />
</appSettings>

擴充建議

  • 加入 Play/Pause/Stop/Next/Previous 方法對應 UI 按鈕。
  • 實作 INotifyPropertyChanged 暴露 CurrentTrack、Progress 供繫結。
  • 支援播放清單儲存/載入 (XML/JSON)。
  • 大量檔案時考慮虛擬化清單或背景掃描避免 UI 凍結。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved