且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

n音讯播放正弦波对于x毫秒使用C#

更新时间:2022-11-29 19:47:18

的SineWaveProvider32类并不需要无限期地提供音频。如果你想嘟嘟有第二(说)的最长期限,那么对于单声道44.1 千赫,您需要提供44,100个样本。 Read方法应返回0时,它已经没有更多的数据源。



为使您的GUI线程不会阻止,你需要摆脱的Thread.Sleep,waveout的的。停止和处置,并简单地开始播放音频(您可能会发现窗口的回调函数相比更可靠)。



然后,当音频播放完毕,您可以关闭和清理waveout的对象。


I am using NAudio to play a sinewave of a given frequency as in the blog post Playback of Sine Wave in NAudio. I just want the sound to play() for x milliseconds and then stop.

I tried a thread.sleep, but the sound stops straightaway. I tried a timer, but when the WaveOut is disposed there is a cross-thread exception.

I tried this code, but when I call beep the program freezes.

public class Beep
{
    public Beep(int freq, int ms)
    {
        SineWaveProvider32 sineWaveProvider = new SineWaveProvider32();
        sineWaveProvider.Amplitude = 0.25f;
        sineWaveProvider.Frequency = freq;

        NAudio.Wave.WaveOut waveOut = new NAudio.Wave.WaveOut(WaveCallbackInfo.FunctionCallback());
        waveOut.Init(sineWaveProvider);
        waveOut.Play();
        Thread.Sleep(ms);
        waveOut.Stop();
        waveOut.Dispose();
    }
}

public class SineWaveProvider32 : NAudio.Wave.WaveProvider32
{
    int sample;

    public SineWaveProvider32()
    {
        Frequency = 1000;
        Amplitude = 0.25f; // Let's not hurt our ears
    }

    public float Frequency { get; set; }
    public float Amplitude { get; set; }

    public override int Read(float[] buffer, int offset, int sampleCount)
    {
        int sampleRate = WaveFormat.SampleRate;
        for (int n = 0; n < sampleCount; n++)
        {
            buffer[n + offset] = (float)(Amplitude * Math.Sin((2 * Math.PI * sample * Frequency) / sampleRate));
            sample++;
            if (sample >= sampleRate)
                sample = 0;
        }
   }

The SineWaveProvider32 class doesn't need to indefinitely provide audio. If you want the beep to have a maximum duration of a second (say), then for mono 44.1 kHz, you need to provide 44,100 samples. The Read method should return 0 when it has no more data to supply.

To make your GUI thread not block, you need to get rid of Thread.Sleep, waveOut.Stop and Dispose, and simply start playing the audio (you may find window callbacks more reliable than function).

Then, when the audio has finished playing, you can close and clean up the WaveOut object.