在Windows應(yīng)用程序中,播放系統(tǒng)聲音是一個常見的需求。本文將詳細(xì)介紹在C#中調(diào)用系統(tǒng)聲音的多種方法,并提供具體的代碼示例。使用 System.Media.SystemSounds 類
基本使用方法
System.Media.SystemSounds
類提供了最簡單的系統(tǒng)聲音播放方式,包括常見的系統(tǒng)提示音。
using System.Media;
// 播放不同類型的系統(tǒng)聲音
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 播放系統(tǒng)聲音
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace AppSystemSound
{
publicclass WindowsApiSoundPlayer
{
// 導(dǎo)入 Windows API 函數(shù)
[DllImport("winmm.dll")]
public static extern int PlaySound(string lpszSoundName, IntPtr hModule, uint dwFlags);
// 聲音播放標(biāo)志
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 默認(rèn)聲音事件
PlaySound(soundEvent, IntPtr.Zero, 0x00040000 | 0x00000000);
}
}
}
public static void PlayWindowsDefaultSound(string soundEvent)
{
// 播放 Windows 默認(rèn)聲音事件
PlaySound(soundEvent, IntPtr.Zero, 0x00040000 | 0x00000000);
}
注意
- 系統(tǒng)聲音播放依賴于系統(tǒng)設(shè)置和音頻硬件
- 某些方法可能需要特定的 Windows 權(quán)限
- 對于復(fù)雜音頻需求,建議使用專業(yè)音頻庫
總結(jié)
C# 提供了多種播放系統(tǒng)聲音的方法,從簡單的 SystemSounds
到復(fù)雜的 Windows API 和第三方庫,開發(fā)者可以根據(jù)具體需求選擇合適的方案。
該文章在 2025/2/24 9:28:36 編輯過