Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generation of mono frequency audio file/signal.
using System;
using NAudio.Wave;
namespace GM.SP.Audio
{
public static class AudioGenerate
{
/// <summary>
/// Generates a mono frequency audio file.
/// </summary>
public static void GenerateAudioFile(string fileName,TimeSpan length,int sampleRate,int frequency)
{
float[] samples = Generate(length, sampleRate, frequency);
WaveFormat format = new WaveFormat(sampleRate, 2);
samples = AudioUtility.Zip(samples, samples);
// convert from samples to bytes
byte[] bytes = new byte[samples.Length * 2];
for(int i = 0, j = 0; i < samples.Length; ++i) {
float sample = samples[i];
short valueShort = (short)(0.5 + sample * ((sample > 0) ? short.MaxValue : 32768));
ushort valueUShort = (ushort)(valueShort + 65536);
bytes[j++] = (byte)valueUShort;
bytes[j++] = (byte)(valueUShort >> 8);
}
// write to file
WaveFileWriter writer = null;
try {
writer = new WaveFileWriter(fileName, format);
writer.Write(bytes, 0, bytes.Length);
writer.Flush();
} finally {
writer?.Dispose();
}
}
/// <summary>
/// Generates a mono frequency signal.
/// </summary>
public static float[] Generate(TimeSpan length, int sampleRate, int frequency)
{
float[] samples = new float[(int)(length.TotalSeconds * sampleRate)];
double step = (2 * Math.PI * frequency) / sampleRate;
double current = 0;
for(int i = 0; i < samples.Length; ++i) {
current += step;
samples[i] = (float)Math.Sin(current);
}
return samples;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.