C# NAudio将一个样本一个样本写入文件
我正在构建一个应用程序,将麦克风中的音频录制到文件(.mp3)中。我希望我的应用程序仅在检测到足够高的振幅时才将数据写入文件。我在保存所选数据时遇到问题。我得到的只是一个快速的失真,甚至与记录的失真都不接近 这是我的代码:C# NAudio将一个样本一个样本写入文件,c#,.net,audio-recording,naudio,voice-recording,C#,.net,Audio Recording,Naudio,Voice Recording,我正在构建一个应用程序,将麦克风中的音频录制到文件(.mp3)中。我希望我的应用程序仅在检测到足够高的振幅时才将数据写入文件。我在保存所选数据时遇到问题。我得到的只是一个快速的失真,甚至与记录的失真都不接近 这是我的代码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; u
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NAudio.Wave;
namespace NAudio_Testing
{
public partial class Form1 : Form
{
int counter = 0;
int passed = 0;
private BufferedWaveProvider bufferedWaveProvider;
WaveIn waveIn;
WaveFileWriter writer;
string output = "C:/Users/klein/AppData/Roaming/Microsoft/Windows/gravacao.mp3";
public Form1()
{
InitializeComponent();
waveIn = new WaveIn();
writer = new WaveFileWriter(output, waveIn.WaveFormat);
waveIn.DataAvailable += new EventHandler<WaveInEventArgs>(new_dataAvailable);
bufferedWaveProvider = new BufferedWaveProvider(waveIn.WaveFormat);
bufferedWaveProvider.DiscardOnBufferOverflow = true;
waveIn.StartRecording();
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval = 1000;
timer1.Start();
}
void new_dataAvailable(object sender, WaveInEventArgs e)
{
for (int i = 0; i < e.BytesRecorded; i+=2)
{
short sample = (short)((e.Buffer[i + 1] << 8) | e.Buffer[i + 0]);
float sample32 = sample / 32768f;
if (sample32 > 0.02) //0.02~0.03
{
writer.WriteSample(sample);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
waveIn.StopRecording();
waveIn.Dispose();
waveIn = null;
writer.Close();
writer = null;
}
private void timer1_Tick(object sender, EventArgs e)
{
textBox1.Text = counter++.ToString();
}
}
}
像这样:
void new_dataAvailable(object sender, WaveInEventArgs e)
{
for (int i = 0; i < e.BytesRecorded; i+=2)
{
short sample = (short)((e.Buffer[i + 1] << 8) | e.Buffer[i + 0]);
float sample32 = sample / 32768f;
writer.WriteByte(e.Buffer[i + 0]);
writer.WriteByte(e.Buffer[i + 1]);
}
}
void new\u数据可用(对象发送方,WaveInEventArgs e)
{
对于(int i=0;i short sample=(short)((e.Buffer[i+1]你的方法基本上是丢弃零点附近的所有样本,而不管当时的整体音频是否响亮。它会使信号失真并加速,因为音频信号通常每秒都有大量的零点交叉
相反,您需要在短时间内测量所有样本的最大音量(时间由您决定,但您可以一次测量1秒)。如果在此期间,任何样本的音量大于指定的最小值,则记录整个数据块
代码的第二个问题是,您实际上没有创建MP3文件。WaveileWriter生成了一个WAV文件。请将文件名更改为以WAV结尾,然后收听该文件以收听录制结果。然后,您需要在录制后的第二步将其转换为MP3。(我有一篇关于如何在格式之间转换的文章).您应该比较样本的绝对值,因为样本是有符号的
if (Abs(sample32) > 0.02) //0.02~0.03
{
writer.WriteSample(sample);
}
if (Abs(sample32) > 0.02) //0.02~0.03
{
writer.WriteSample(sample);
}