/// <summary> /// Initializes a new instance of the <see cref="SoundEncoder"/> class. /// </summary> /// <param name="filename">A relative or absolute path for the file that the current <see cref="SoundEncoder"/> object will encapsulate.</param> /// <param name="sampleRate">The samples rate of the sound, in samples per second.</param> /// <param name="channelCount">The number of channels of the sound.</param> /// <inheritdoc /> public SoundEncoder(string filename, int sampleRate, int channelCount) { // Find a suitable writer for the given audio stream writer = SoundProcessorFactory.GetWriter(filename, sampleRate, channelCount); if (writer == null) { throw new NotSupportedException("Failed to open audio stream. Invalid audio format or not supported."); } // Retrieve the attributes of the sound ChannelCount = writer.ChannelCount; SampleRate = writer.SampleRate; }
/// <summary> /// Save the audio samples into sound file. /// </summary> /// <param name="filename">The path of sound file to be save.</param> public void Save(string filename) { lock (this) { long offset = Decoder.SampleOffset; Decoder.Seek(0); using (var writer = SoundProcessorFactory.GetWriter(filename, SampleRate, ChannelCount)) { int bufferSize = SampleRate * ChannelCount; var samples = new short[bufferSize]; long read = 0; while ((read = Decoder.Decode(samples, bufferSize)) > 0) { writer.Write(samples, 0, (int)read); } } Decoder.Seek(offset); } }
/// <summary> /// Save the audio samples into an array of byte. /// </summary> /// <typeparam name="T">The desired sound writer to use.</typeparam> /// <returns>An array of bytes which an audio samples in binary form.</returns> public byte[] Save <T>() where T : SoundWriter, new() { lock (this) { long offset = Decoder.SampleOffset; Decoder.Seek(0); using (var stream = new MemoryStream()) using (var writer = SoundProcessorFactory.GetWriter <T>(stream, SampleRate, ChannelCount)) { int bufferSize = SampleRate * ChannelCount; var samples = new short[bufferSize]; while (Decoder.Decode(samples, bufferSize) > 0) { writer.Write(samples, 0, samples.Length); } Decoder.Seek(offset); return(stream.ToArray()); } } }