Skip to content

Instantly share code, notes, and snippets.

@GregaMohorko
Last active April 15, 2017 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GregaMohorko/d576fd74c9dda5cdaa9b1a86f7edd0c9 to your computer and use it in GitHub Desktop.
Save GregaMohorko/d576fd74c9dda5cdaa9b1a86f7edd0c9 to your computer and use it in GitHub Desktop.
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