/// <summary> /// Generate a wav loop stream containing a 440Hz sine wave. /// </summary> /// <param name="nrSeconds">the length of the wav stream in seconds</param> /// <returns>a loop stream containing 'nrSeconds' of wav sine wave</returns> private LoopStream GenerateSineWave(uint nrSeconds) { // Fill the data array with sample data var data = new WaveDataChunk(); var numSamples = waveFormat.SampleRate * waveFormat.Channels * nrSeconds; data.AudioSamples = new short[numSamples]; var amplitude = 32760; // Max amplitude for 16-bit audio var freq = 440.0f; // Concert A: 440Hz // The "angle" used in the function, adjusted for the number of channels and sample rate. // This value is like the period of the wave. double t = (Math.PI * 2 * freq) / (waveFormat.SampleRate * waveFormat.Channels); for (uint i = 0; i < numSamples - waveFormat.Channels; i++) { // Fill with a simple sine wave at max amplitude for (int channel = 0; channel < waveFormat.Channels; channel++) { data.AudioSamples[i + channel] = Convert.ToInt16(amplitude * Math.Sin(t * i)); } } data.Length = (uint)(data.AudioSamples.Length * (waveFormat.BitsPerSample / 8)); return(CreateStream(data)); }
/// <summary> /// Create a loop stream of the wav data. /// </summary> /// <param name="data">wav data</param> /// <returns>a loop stream containing the wav data</returns> private LoopStream CreateStream(WaveDataChunk data) { if (data == null) { return(null); } var stream = new MemoryStream(); var writer = new BinaryWriter(stream); // Write the wav header var header = new AudioHeader(); writer.Write(header.GetRiffHeader(waveFormat, data.Length)); // Write the data chunk foreach (short dataPoint in data.AudioSamples) { writer.Write(dataPoint); } writer.Seek(4, SeekOrigin.Begin); var streamsize = (uint)writer.BaseStream.Length; writer.Write(streamsize - 8); writer.Flush(); stream.Position = 0; return(new LoopStream(stream, waveFormat)); }
/// <summary> /// Get silence data. /// </summary> private WaveDataChunk GetSilence(uint nrSeconds) { // Fill the data array with silence samples. var data = new WaveDataChunk(); var numSamples = waveFormat.SampleRate * waveFormat.Channels * nrSeconds; data.AudioSamples = new short[numSamples]; data.Length = (uint)(data.AudioSamples.Length * (waveFormat.BitsPerSample / 8)); return(data); }
/// <summary> /// Get silence data. /// </summary> public WaveDataChunk GetSilence(uint nrSeconds) { // Fill the data array with silence samples. var data = new WaveDataChunk(); var numSamples = waveFormat.SampleRate * waveFormat.Channels * nrSeconds; data.AudioSamples = new short[numSamples]; for (uint i = 0; i < numSamples - 1; i++) { for (int channel = 0; channel < waveFormat.Channels; channel++) { data.AudioSamples[i + channel] = 0; } } data.Length = (uint)(data.AudioSamples.Length * (waveFormat.BitsPerSample / 8)); return(data); }