NAudio plays a sine wave in milliseconds using C #

I am using NAudio to reproduce the sine frequency of a given frequency, as in the blog post Play Sine Wave in NAudio . I just want the sound to play () in milliseconds and then stop.

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

I tried this code, but when I call a 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 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; } } 
+6
c # sine wave naudio
source share
2 answers

The SineWaveProvider32 class does not need to endlessly provide audio. If you want the audio signal 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 if it has no more data.

To prevent your GUI thread from blocking, you need to get rid of Thread.Sleep, waveOut.Stop and Dispose and just start playing the sound (you can find window callbacks more reliable than the function).

Then, when the sound is finished, you can close and clear the WaveOut object.

+4
source share

Post a blog post Pass variables to a new thread in C # on how to pass variables to another thread.

I think you want to do something like create a stream that plays your sound, creates a timer, and starts the stream. When the timer expires, destroy the stream, and when the stream closes, it will do all the cleaning.

0
source share

All Articles