本文整理汇总了C#中NAudio.Wave.WaveFileWriter类的典型用法代码示例。如果您正苦于以下问题:C# WaveFileWriter类的具体用法?C# WaveFileWriter怎么用?C# WaveFileWriter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
WaveFileWriter类属于NAudio.Wave命名空间,在下文中一共展示了WaveFileWriter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: button_rec_Click
//Кнопка "Запись"
private void button_rec_Click(object sender, EventArgs e)
{
button_stop.Enabled = true;
timer.Start();
ind = 1;
try
{
waveIn = new WaveIn();
waveIn.DeviceNumber = 0;//Дефолтное устройство для записи (если оно имеется)
waveIn.DataAvailable += waveIn_DataAvailable;//Прикрепляем к событию DataAvailable обработчик, возникающий при наличии записываемых данных
waveIn.RecordingStopped += waveIn_RecordingStopped;//Прикрепляем обработчик завершения записи
waveIn.WaveFormat = new WaveFormat(8000, 1);//Формат wav-файла - принимает параметры - частоту дискретизации и количество каналов(здесь mono)
writer = new WaveFileWriter(outputFilename, waveIn.WaveFormat);//Инициализируем объект WaveFileWriter
waveIn.StartRecording();//Начало записи
button_play.Enabled = false;
button_rec.Enabled = false;
numeric.Enabled = false;
}
catch (Exception ex)
{
button_play.Enabled = true;
button_rec.Enabled = true;
numeric.Enabled = true;
MessageBox.Show(ex.Message);
}
}
示例2: Recorder
public Recorder()
{
int waveInDevices = WaveIn.DeviceCount;
//for (int waveInDevice = 0; waveInDevice < waveInDevices; waveInDevice++)
//{
// WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice);
// comboBox1.Items.Add(string.Format("Device {0}: {1}, {2} channels", waveInDevice, deviceInfo.ProductName, deviceInfo.Channels));
//}
waveIn = new WaveIn();
waveIn.DeviceNumber = 0;
waveIn.DataAvailable += waveIn_DataAvailable;
waveIn.RecordingStopped += waveIn_RecordingStopped;
int sampleRate = 16000; // 16 kHz
int channels = 1; // mono
int bits = 16;
recordingFormat = new WaveFormat(sampleRate, bits, channels);
waveIn.WaveFormat = recordingFormat;
string path = "C:\\temp";
if( !Directory.Exists(path) )
{
Directory.CreateDirectory(path);
}
TempWavFileName = String.Format("{0}\\{1}.wav", path, Guid.NewGuid().ToString());
writer = new WaveFileWriter(TempWavFileName, recordingFormat);
}
示例3: Main
static void Main(string[] args)
{
// for recording
waveFileWriter = new WaveFileWriter(@"C:\rec\out.wav", new WaveFormat(44100, 2));
var sound = new MySound();
sound.SetWaveFormat(44100, 2);
sound.init();
waveOut = new WaveOut();
waveOut.Init(sound);
waveOut.Play();
ConsoleKeyInfo keyInfo;
bool loop = true;
while (loop)
{
keyInfo = Console.ReadKey();
if (keyInfo.Key == ConsoleKey.Q)
{
waveOut.Stop();
waveOut.Dispose();
waveFileWriter.Close();
waveFileWriter.Dispose();
loop = false;
}
}
}
示例4: ConcatenateWav
/// <summary>
/// Merge multiple .wav files together and save the output.
/// </summary>
/// <param name="outputFile">The path to save the output to.</param>
/// <param name="sourceFiles">An IEnumerable list of files to merge.</param>
private static void ConcatenateWav(string outputFile, IEnumerable<string> sourceFiles) {
byte[] buffer = new byte[1024];
WaveFileWriter waveFileWriter = null;
try {
foreach (string sourceFile in sourceFiles) {
using (WaveFileReader reader = new WaveFileReader(sourceFile)) {
if (waveFileWriter == null) {
// first time in create new Writer
waveFileWriter = new WaveFileWriter(outputFile, reader.WaveFormat);
}
else {
if (!reader.WaveFormat.Equals(waveFileWriter.WaveFormat)) {
throw new InvalidOperationException("Can't concatenate WAV Files that don't share the same format");
}
}
int read;
while ((read = reader.Read(buffer, 0, buffer.Length)) > 0) {
waveFileWriter.WriteData(buffer, 0, read);
}
}
}
}
finally {
if (waveFileWriter != null) {
waveFileWriter.Dispose();
}
}
}
示例5: ReaderShouldReadBackSameDataWrittenWithWrite
public void ReaderShouldReadBackSameDataWrittenWithWrite()
{
var ms = new MemoryStream();
var testSequence = new byte[] { 0x1, 0x2, 0xFF, 0xFE };
using (var writer = new WaveFileWriter(new IgnoreDisposeStream(ms), new WaveFormat(16000, 24, 1)))
{
writer.Write(testSequence, 0, testSequence.Length);
}
// check the Reader can read it
ms.Position = 0;
using (var reader = new WaveFileReader(ms))
{
Assert.AreEqual(16000, reader.WaveFormat.SampleRate, "Sample Rate");
Assert.AreEqual(24, reader.WaveFormat.BitsPerSample, "Bits Per Sample");
Assert.AreEqual(1, reader.WaveFormat.Channels, "Channels");
Assert.AreEqual(testSequence.Length, reader.Length, "File Length");
var buffer = new byte[600]; // 24 bit audio, block align is 3
int read = reader.Read(buffer, 0, buffer.Length);
Assert.AreEqual(testSequence.Length, read, "Data Length");
for (int n = 0; n < read; n++)
{
Assert.AreEqual(testSequence[n], buffer[n], "Byte " + n);
}
}
}
示例6: FlushUpdatesHeaderEvenIfDisposeNotCalled
public void FlushUpdatesHeaderEvenIfDisposeNotCalled()
{
var ms = new MemoryStream();
var testSequence = new byte[] { 0x1, 0x2, 0xFF, 0xFE };
var testSequence2 = new byte[] { 0x3, 0x4, 0x5 };
var writer = new WaveFileWriter(new IgnoreDisposeStream(ms), new WaveFormat(16000, 24, 1));
writer.Write(testSequence, 0, testSequence.Length);
writer.Flush();
// BUT NOT DISPOSED
// another write that was not flushed
writer.Write(testSequence2, 0, testSequence2.Length);
// check the Reader can read it
ms.Position = 0;
using (var reader = new WaveFileReader(ms))
{
Assert.AreEqual(16000, reader.WaveFormat.SampleRate, "Sample Rate");
Assert.AreEqual(24, reader.WaveFormat.BitsPerSample, "Bits Per Sample");
Assert.AreEqual(1, reader.WaveFormat.Channels, "Channels");
Assert.AreEqual(testSequence.Length, reader.Length, "File Length");
var buffer = new byte[600]; // 24 bit audio, block align is 3
int read = reader.Read(buffer, 0, buffer.Length);
Assert.AreEqual(testSequence.Length, read, "Data Length");
for (int n = 0; n < read; n++)
{
Assert.AreEqual(testSequence[n], buffer[n], "Byte " + n);
}
}
writer.Dispose(); // to stop the finalizer from moaning
}
示例7: sourceStreamDataAvailable
private void sourceStreamDataAvailable(object sender, WaveInEventArgs e)
{
string path = outputPath + "wavsam" + nFiles + ".wav";
writer = new WaveFileWriter(path, waveFormat);
writer.Write(e.Buffer, 0, e.Buffer.Length);
writer.Flush();
writer.Close();
nFiles++;
Process process = new Process();
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = "praatcon.exe";
String male;
if (isMale) male = "yes"; else male = "no";
process.StartInfo.Arguments = "extract_measures.praat " + path + " " + male;
// process.StartInfo.RedirectStandardOutput = true;
process.Start();
process.WaitForExit();
ResultEventArgs args = new ResultEventArgs();
// args.text = output;
OnResults(args);
// args.nWords = err.Length;
}
示例8: Transcode
public async Task Transcode(CancellationToken ct, IWaveStreamProvider stream, Stream targetStream)
{
using (var fileWriter = new NAudio.Wave.WaveFileWriter(targetStream, stream.WaveFormat))
{
await stream.Stream.CopyToAsync(fileWriter);
}
}
示例9: CanDownsampleAnMp3File
public void CanDownsampleAnMp3File()
{
string testFile = @"D:\Audio\Music\Coldplay\Mylo Xyloto\03 - Paradise.mp3";
if (!File.Exists(testFile)) Assert.Ignore(testFile);
string outFile = @"d:\test22.wav";
using (var reader = new AudioFileReader(testFile))
{
// downsample to 22kHz
var resampler = new WdlResamplingSampleProvider(reader, 22050);
var wp = new SampleToWaveProvider(resampler);
using (var writer = new WaveFileWriter(outFile, wp.WaveFormat))
{
byte[] b = new byte[wp.WaveFormat.AverageBytesPerSecond];
while (true)
{
int read = wp.Read(b, 0, b.Length);
if (read > 0)
writer.Write(b, 0, read);
else
break;
}
}
//WaveFileWriter.CreateWaveFile(outFile, );
}
}
示例10: ConvertWavTo10SecondWavs
private void ConvertWavTo10SecondWavs(FileInfo inputFile)
{
var samplesOutWav = @"..\..\..\samples\wav10seconds\";
using (var inAudio = new WaveFileReader(inputFile.FullName))
{
//Calculate required byte[] buffer.
var buffer = new byte[10*inAudio.WaveFormat.AverageBytesPerSecond];//Assume average will be constant for WAV format.
int index = 0;
do
{
var outFile = string.Format("{0}{1}.{2:0000}.wav",
samplesOutWav, inputFile.Name.Replace(inputFile.Extension, string.Empty), index);
int bytesRead = 0;
do
{
bytesRead = inAudio.Read(buffer, 0, buffer.Length - bytesRead);
} while (bytesRead > 0 && bytesRead < buffer.Length);
//Write new file
using (var waveWriter = new WaveFileWriter(outFile, inAudio.WaveFormat))
{
waveWriter.Write(buffer, 0, buffer.Length);
}
index++;
} while (inAudio.Position < inAudio.Length);
}
}
示例11: buttonStartRecording_Click
private void buttonStartRecording_Click(object sender, EventArgs e)
{
if (waveIn == null)
{
if(outputFilename == null)
{
buttonSelectOutputFile_Click(sender, e);
}
if(outputFilename == null)
{
return;
}
if (radioButtonWaveIn.Checked)
{
waveIn = new WaveIn();
waveIn.WaveFormat = new WaveFormat(8000, 1);
}
else
{
waveIn = new WasapiCapture((MMDevice)comboDevices.SelectedItem);
// go with the default format as WASAPI doesn't support SRC
}
writer = new WaveFileWriter(outputFilename, waveIn.WaveFormat);
waveIn.DataAvailable += new EventHandler<WaveInEventArgs>(waveIn_DataAvailable);
waveIn.RecordingStopped += new EventHandler(waveIn_RecordingStopped);
waveIn.StartRecording();
buttonStartRecording.Enabled = false;
}
}
示例12: RecordSound
public static void RecordSound(string name)
{
int waveDeviceCount = WaveIn.DeviceCount;
//detect presence of recording hardware
if (waveDeviceCount > 0)
{
inputDevice = 0;
}
else
{
MessageBox.Show("No recording hardware detected", "iMasomoAdmin", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
wordName = name;
try
{
waveIn = new WaveIn();
waveIn.DeviceNumber = inputDevice;
waveIn.WaveFormat = new NAudio.Wave.WaveFormat(44100, WaveIn.GetCapabilities(inputDevice).Channels);
//in the presence of incoming data, write the data to a buffer
waveIn.DataAvailable += waveIn_DataAvailable;
waveWriter = new WaveFileWriter(Environment.CurrentDirectory + @"\Media\" + wordName + ".wav", waveIn.WaveFormat);
waveIn.StartRecording();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
示例13: Processing
private void Processing()
{
try
{
using (var waveWriterYour = new WaveFileWriter(@"F:\Desktop\\Recordshit\\" + Environment.UserName + " - " + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss-fff") + ".wav", new WaveFormat(48000, 16, 2)))
while (true)
{
byte[] bufBytes;
if (BufferCollection.TryTake(out bufBytes, Timeout.Infinite))
{
if (bufBytes.Length == 0 || !_socketClient.Connected)
break;
_socketClient.Send(bufBytes);
waveWriterYour.Write(bufBytes, 0, bufBytes.Length);
waveWriterYour.Flush();
}
else
{
break;
}
}
}
catch (Exception e)
{
}
}
示例14: Form1
public Form1()
{
if (save)
writer = new WaveFileWriter("test.wav", new WaveFormat(44100, 1));
Control.CheckForIllegalCrossThreadCalls = false;
//35
//40-60
//60-100
//100-300
//600-900
//900-1800
//1800-3500
//3500-7500
//7500-12000
//12000-18000
//18000
var filters = new EqualizerFilters();
table = new float[filters.Filters.Count];
for (int i = 0; i < table.Length; i++)
table[i] = 1;
solver = new FIRSolver2(OpenCLNet.OpenCL.GetPlatform(0), filters.Filters, 2048);
solver.SetMulTable(table);
InitializeComponent();
asio = new Asio.Asio(Asio.Asio.InstalledDrivers.ElementAt(0));
asio.ProcessAudio = ProcessAudio;
var asioThread = new Thread(new ThreadStart(asio.Start));
asioThread.IsBackground = true;
asioThread.Priority = ThreadPriority.Highest;
asioThread.Start();
}
示例15: AudioRecorder
public AudioRecorder(int microphone)
{
waveIn = new WaveIn();
waveIn.DeviceNumber = microphone;
waveIn.WaveFormat = new WaveFormat(44100, 1);
bufferedWaveProvider = new BufferedWaveProvider(waveIn.WaveFormat);
writer = new WaveFileWriter(Settings.Default.tempSoundLocation, waveIn.WaveFormat);
}