张赐荣——一位视障程序员。
赐荣小站: www.prc.cx

張賜榮

张赐荣的技术博客

博客园 首页 新随笔 联系 订阅 管理

用 Beep 函数,让你的主板也会“唱歌”。
Beep 可以通过控制主板扬声器的发声频率和节拍来演奏美妙的旋律。
本文就通过C#演示,调用Beep函数,演奏生日快乐歌。
首先我们来看下 Beep 函数原型:
依赖库:LIB:kernel32.lib,DLL:kernel32.dll,
BOOL Beep([in] DWORD dwFreq, [in] DWORD dwDuration);
参数:
dwFreq 指定要发出的频率(从37Hz到32767Hz),
dwDuration 指定发音的时长,单位是毫秒。
返回值:调用成功返回true,失败返回false。

C#演示

using System;
using System.Runtime.InteropServices;

namespace App
{
    public class Program
    {
        [DllImport("kernel32.dll", EntryPoint = "Beep")] extern public static bool Kernel32_Beep(int frequency_Hz, int duration_ms);

        static int Main(string[] args)
        {
            string Spectrum = "523,300|523,300|578,500|523,500|698,500|659,900|523,300|523,300|578,500|523,500|784,500|698,900|523,300|523,300|1046,500|880,500|698,500|659,500|578,500|932,300|932,300|880,500|698,500|784,500|698,1000";
            string[] nodes = Spectrum.Split('|');
            foreach (var node in nodes)
            {
                string[] tmp = node.Split(',');
                int frequency = int.Parse(tmp[0]);
                int duration = int.Parse(tmp[1]);
                Kernel32_Beep(frequency,duration);
            }
            Console.WriteLine("Happy birthday to you!");
            Console.ReadLine();
            return (0);
        }
    }
}

参考:
[1] Beep 函数: https://docs.microsoft.com/zh-cn/windows/win32/api/utilapiset/nf-utilapiset-beep#main
[2] 音符频率关系对应表: https://pages.mtu.edu/~suits/notefreqs.html

posted on 2022-02-17 10:12  张赐荣  阅读(634)  评论(0编辑  收藏  举报

感谢访问张赐荣的技术分享博客!
博客地址:https://cnblogs.com/netlog/
知乎主页:https://www.zhihu.com/people/tzujung-chang
个人网站:https://prc.cx/