【问题标题】:Is it possible to generate a constant sound in C# while adjusting its frequency?是否可以在调整频率的同时在 C# 中生成恒定的声音?
【发布时间】:2011-09-30 22:53:55
【问题描述】:

是否可以在 C# 中生成恒定的声音并在其运行时操纵其频率?

我尝试过这样的事情:

for (int i = 500; i < 15000; i += 1)
{
    Console.Beep(i, 500));
}

但由于是同步的,循环会等待每次哔声完成。所以我尝试了这个:

for (int i = 500; i < 15000; i += 1)
{
    new Thread(x => Console.Beep(i, 500)).Start();
}

我认为这将是产生频率不断增加的恒定声音的开始。但是,它仍然会结结巴巴。有没有办法做到这一点,但更顺利?

【问题讨论】:

    标签: c# .net winforms audio


    【解决方案1】:

    如果您想实时执行此操作(即根据用户输入动态更改频率),这将非常困难,并且需要您编写软件合成器。在这种情况下,您可能想尝试使用像 NAudio 这样的库(尽管我不能 100% 确定 NAudio 会进行实时合成)。

    另一方面,如果你只是想预先生成一个连续升调的 WAV 文件,然后播放它,这非常容易。

    编辑:第三种选择是播放 MIDI 声音并将控制更改消息发送到 MIDI 设备,以逐渐将 portmanteau 应用于播放音符。这也很简单,但缺点是您无法确定它在其他人的计算机上的确切声音。

    【讨论】:

    • 你可以百分百确定...mark-dot-net.blogspot.com/2009/10/…
    • 谢谢 :) System.Media.SoundPlayer 到了。
    • @DarkSquirrel42 哇哦。正弦波看起来正是我想要做的。
    • @Alex:是的,我会使用 DarkSquirrel 的例子,虽然学习如何编写 WAV 文件也很有用。
    • @DarkSquirrel42:你知道延迟是多少吗?这看起来很容易使用。
    【解决方案2】:

    generate sine wave 下方的代码。您可以更改频率和其他参数

        private void TestSine()
        {
            IntPtr format;
            byte[] data;
            GetSineWave(1000, 100, 44100, -1, out format, out data);
            WaveWriter ww = new WaveWriter(File.Create(@"d:\work\sine.wav"),
                AudioCompressionManager.FormatBytes(format));
            ww.WriteData(data);
            ww.Close();
        }
    
        private void GetSineWave(double freq, int durationMs, int sampleRate, short decibel, out IntPtr format, out byte[] data)
        {
            short max = dB2Short(decibel);//short.MaxValue
            double fs = sampleRate; // sample freq
            int len = sampleRate * durationMs / 1000;
            short[] data16Bit = new short[len];
            for (int i = 0; i < len; i++)
            {
                double t = (double)i / fs; // current time
                data16Bit[i] = (short)(Math.Sin(2 * Math.PI * t * freq) * max);
            }
            IntPtr format1 = AudioCompressionManager.GetPcmFormat(1, 16, (int)fs);
            byte[] data1 = new byte[data16Bit.Length * 2];
            Buffer.BlockCopy(data16Bit, 0, data1, 0, data1.Length);
            format = format1;
            data = data1;
        }
    
        private static short dB2Short(double dB)
        {
            double times = Math.Pow(10, dB / 10);
            return (short)(short.MaxValue * times);
        }
    

    【讨论】:

      猜你喜欢
      • 2010-12-11
      • 1970-01-01
      • 2019-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-18
      • 2012-05-27
      • 1970-01-01
      相关资源
      最近更新 更多