在Windows應用程序中,播放系統聲音是一個常見的需求。本文將詳細介紹在C#中調用系統聲音的多種方法,并提供具體的代碼示例。使用 System.Media.SystemSounds 類
基本使用方法
System.Media.SystemSounds
類提供了最簡單的系統聲音播放方式,包括常見的系統提示音。
using System.Media;
// 播放不同類型的系統聲音
SystemSounds.Asterisk.Play(); // 信息提示音
SystemSounds.Beep.Play(); // 基本蜂鳴聲
SystemSounds.Exclamation.Play();// 警告聲
SystemSounds.Hand.Play(); // 錯誤提示音
SystemSounds.Question.Play(); // 詢問聲
完整示例代碼
using System.Media;
namespace AppSystemSound
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnPlayAsterisk_Click(object sender, EventArgs e)
{
SystemSounds.Asterisk.Play();
}
private void btnPlayBeep_Click(object sender, EventArgs e)
{
SystemSounds.Beep.Play();
}
private void btnPlayExclamation_Click(object sender, EventArgs e)
{
SystemSounds.Exclamation.Play();
}
}
}
?使用 Windows API 播放聲音
通過 winmm.dll 播放系統聲音
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace AppSystemSound
{
publicclass WindowsApiSoundPlayer
{
// 導入 Windows API 函數
[DllImport("winmm.dll")]
public static extern int PlaySound(string lpszSoundName, IntPtr hModule, uint dwFlags);
// 聲音播放標志
publicconst uint SND_FILENAME = 0x00020000;
publicconst uint SND_SYNC = 0x0000;
public static void PlaySystemSound(string soundPath)
{
PlaySound(soundPath, IntPtr.Zero, SND_FILENAME | SND_SYNC);
}
public static void PlayWindowsDefaultSound(string soundEvent)
{
// 播放 Windows 默認聲音事件
PlaySound(soundEvent, IntPtr.Zero, 0x00040000 | 0x00000000);
}
}
}
public static void PlayWindowsDefaultSound(string soundEvent)
{
// 播放 Windows 默認聲音事件
PlaySound(soundEvent, IntPtr.Zero, 0x00040000 | 0x00000000);
}
注意
- 系統聲音播放依賴于系統設置和音頻硬件
- 某些方法可能需要特定的 Windows 權限
- 對于復雜音頻需求,建議使用專業音頻庫
總結
C# 提供了多種播放系統聲音的方法,從簡單的 SystemSounds
到復雜的 Windows API 和第三方庫,開發者可以根據具體需求選擇合適的方案。
該文章在 2025/2/24 9:28:36 編輯過