C# 调用系统声音的完整指南
				
									
					
					
						|  | 
							admin 2025年2月23日 22:37
								本文热度 1732 | 
					
				 
				在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 编辑过