在Windows应用程序中,播放系统声音是一个常见的需求。本文将详细介绍在C#中调用系统声音的多种方法,并提供具体的代码示例。
System.Media.SystemSounds
类提供了最简单的系统声音播放方式,包括常见的系统提示音。
C#using System.Media;
// 播放不同类型的系统声音
SystemSounds.Asterisk.Play(); // 信息提示音
SystemSounds.Beep.Play(); // 基本蜂鸣声
SystemSounds.Exclamation.Play();// 警告声
SystemSounds.Hand.Play(); // 错误提示音
SystemSounds.Question.Play(); // 询问声
C#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();
}
}
}
C#using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace AppSystemSound
{
public class WindowsApiSoundPlayer
{
// 导入 Windows API 函数
[DllImport("winmm.dll")]
public static extern int PlaySound(string lpszSoundName, IntPtr hModule, uint dwFlags);
// 声音播放标志
public const uint SND_FILENAME = 0x00020000;
public const 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);
}
}
}
C#public static void PlayWindowsDefaultSound(string soundEvent)
{
// 播放 Windows 默认声音事件
PlaySound(soundEvent, IntPtr.Zero, 0x00040000 | 0x00000000);
}
C# 提供了多种播放系统声音的方法,从简单的 SystemSounds
到复杂的 Windows API 和第三方库,开发者可以根据具体需求选择合适的方案。
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!