萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 播放背景音樂綜合方案:五種技術路線對比

方案對比總覽

方案支援格式複雜度延遲適用場景
1. WinMM PlaySoundWAV極低低簡單提示音
2. System.Media.SoundPlayerWAV低低WinForms/WPF 簡單播放
3. MCI (mciSendString)MP3、WAV、AVI、MID 等中中需播放壓縮格式、無額外依賴
4. Windows Media Player COM (AxWMP)系統支援所有格式中高高完整媒體播放器功能
5. NAudio / CSCore (純托管)豐富 (MP3, FLAC, OGG...)中低專業音訊應用、特效處理

方案 1:WinMM PlaySound (最簡單)


using System.Runtime.InteropServices;

public class WinMMPlayer
{
    [DllImport("winmm.dll", SetLastError = true)]
    private static extern bool PlaySound(string pszSound, IntPtr hmod, uint fdwSound);

    private const uint SND_ASYNC = 0x0001;  // 非同步
    private const uint SND_FILENAME = 0x00020000;  // 檔案名
    private const uint SND_LOOP = 0x0008;   // 循環

    public void PlayLoop(string wavFile)
    {
        PlaySound(wavFile, IntPtr.Zero, SND_FILENAME | SND_ASYNC | SND_LOOP);
    }

    public void Stop()
    {
        PlaySound(null, IntPtr.Zero, 0);
    }
}

方案 2:System.Media.SoundPlayer (標準庫)


using System.Media;

public class SimpleWavPlayer
{
    private SoundPlayer player = new SoundPlayer();
    
    public void PlayLoop(string wavPath)
    {
        player.SoundLocation = wavPath;
        player.LoadAsync();  // 非同步載入
        player.PlayLooping();
    }
    
    public void Stop() => player.Stop();
}

方案 3:MCI 命令字串 (支援 MP3)


using System.Runtime.InteropServices;

public class MciPlayer : IDisposable
{
    [DllImport("winmm.dll")]
    private static extern uint mciSendString(string command, StringBuilder buffer, uint bufferSize, IntPtr hwndCallback);
    
    private string alias = "media_alias";
    
    public void Open(string filePath)
    {
        mciSendString($"close {alias}", null, 0, IntPtr.Zero);
        string cmd = $"open \"{filePath}\" type mpegvideo alias {alias}";
        uint err = mciSendString(cmd, null, 0, IntPtr.Zero);
        if (err != 0) throw new Exception($"MCI 開啟失敗: {err}");
    }
    
    public void Play(bool loop = true)
    {
        string cmd = loop ? $"play {alias} repeat" : $"play {alias}";
        mciSendString(cmd, null, 0, IntPtr.Zero);
    }
    
    public void Stop()
    {
        mciSendString($"stop {alias}", null, 0, IntPtr.Zero);
    }
    
    public void Dispose()
    {
        mciSendString($"close {alias}", null, 0, IntPtr.Zero);
    }
}

方案 4:AxWindowsMediaPlayer COM 元件

  1. 工具箱 → 選擇項目 → COM 元件 → Windows Media Player
  2. 拖放至表單 → axWindowsMediaPlayer1
  3. 設定 URL 屬性或呼叫 Ctlcontrols.play()

// 循環播放清單
private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
    if (e.newState == (int)WMPLib.WMPPlayState.wmppsMediaEnded)
    {
        // 切換下一首
        axWindowsMediaPlayer1.URL = nextTrackPath;
        axWindowsMediaPlayer1.Ctlcontrols.play();
    }
}

方案 5:NAudio (推薦現代專案)


Install-Package NAudio

using NAudio.Wave;

public class AudioPlayer : IDisposable
{
    private IWavePlayer waveOut;
    private AudioFileReader audioFile;
    
    public void Play(string filePath)
    {
        Stop();
        waveOut = new WaveOutEvent();
        audioFile = new AudioFileReader(filePath);
        waveOut.Init(audioFile);
        waveOut.Play();
    }
    
    public void Stop()
    {
        waveOut?.Stop();
        audioFile?.Dispose();
        audioFile = null;
        waveOut?.Dispose();
        waveOut = null;
    }
    
    public void Dispose() => Stop();
}

選型建議

  • **僅需簡單 WAV 提示音** → SoundPlayer 或 PlaySound。
  • **需播放 MP3、無額外依賴** → MCI。
  • **完整播放器 UI、播放清單** → AxWindowsMediaPlayer。
  • **專業音訊處理、特效、跨平台** → NAudio / CSCore。
  • **WPF 專案** → MediaPlayer / MediaElement (內建)。
copyright © 萬盛學電腦網 all rights reserved