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

C# 播放背景音樂總結:WinMM、SoundPlayer、MCI、Windows Media Player 四種方案比較

     編輯:更多程式設計知識

WinForm 專案播放背景音樂有多種方案,各有優缺點。本文整理四種常見做法並提供程式碼片段。

方案一:WinMM.dll 非托管 API


using System.Runtime.InteropServices;
class Audio {
    [DllImport("winmm.dll")]
    public static extern bool PlaySound(string filename, int hmod, int flags);
    public void Play() { PlaySound(@"d:\qm.wav", 0, 1); }
}
  • 旗標 1 (SND_SYNC) 同步播放,9 (SND_ASYNC | SND_LOOP) 非同步循環。
  • 僅支援 WAV,無音量控制。

方案二:系統內建音效


System.Media.SystemSounds.Asterisk.Play();
System.Media.SystemSounds.Beep.Play();
// Exclamation, Hand, Question 等
  • 無需檔案,適合簡單提示音。

方案三:SoundPlayer 播放 WAV


var sp = new System.Media.SoundPlayer();
sp.SoundLocation = @"D:\10sec.wav";
sp.PlayLooping();  // 循環播放
  • 托管類別,用法簡單,支援非同步、循環。
  • 僅限 WAV 格式。

方案四:MCI 命令字串播放 MP3/AVI


using System.Runtime.InteropServices;
class Media {
    [DllImport("winmm.dll")]
    static extern uint mciSendString(string cmd, string ret, uint retLen, uint hwnd);
    public void PlayMp3() {
        mciSendString("close temp_alias", null, 0, 0);
        mciSendString(@"open ""E:\Music\青花瓷.mp3"" alias temp_alias", null, 0, 0);
        mciSendString("play temp_alias repeat", null, 0, 0);
    }
}
  • 支援 MP3、AVI、MPEG 等多媒體格式。
  • 命令字串靈活,可控制播放位置、速度、音量。
  • 錯誤處理較繁瑣。

方案五:Windows Media Player COM 元件

  1. 工具箱 → 選擇項目 → COM 元件 → Windows Media Player。
  2. 拖放 axWindowsMediaPlayer 到表單,設定 URL 屬性。
  3. 循環播放清單:

private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e) {
    if (e.newState == (int)WMPLib.WMPPlayState.wmppsMediaEnded) {
        new Thread(() => {
            axWindowsMediaPlayer1.URL = @"E:\Music\SomeOne.avi";
            axWindowsMediaPlayer1.Ctlcontrols.play();
        }).Start();
    }
}

選擇建議

需求推薦方案
簡單 WAV 提示音SoundPlayer 或 SystemSounds
背景音樂循環 (MP3)MCI 或 WMP COM
完整播放控制 (進度、音量、清單)WMP COM
跨平台 / .NET CoreNAudio、MediaPlayerElement (UWP) 等托管庫
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved