有没有办法,在C#中,在.NET上,“在运行中”处理音频?例如,如果我想在录制时评估音频AT的平均强度(为此,我需要持续几毫秒)。
答案 0 :(得分:17)
麦克风的初始化和录制的声音处理:
private void Initialize()
{
Microphone microphone = Microphone.Default;
// 100 ms is a minimum buffer duration
microphone.BufferDuration = TimeSpan.FromMilliseconds(100);
DispatcherTimer updateTimer = new DispatcherTimer()
{
Interval = TimeSpan.FromMilliseconds(0.1)
};
updateTimer.Tick += (s, e) =>
{
FrameworkDispatcher.Update();
};
updateTimer.Start();
byte[] microphoneSignal = new byte[microphone.GetSampleSizeInBytes(microphone.BufferDuration)];
microphone.BufferReady += (s, e) =>
{
int microphoneDataSize = microphone.GetData(microphoneSignal);
double amplitude = GetSignalAmplitude(microphoneSignal);
// do your stuff with amplitude here
};
microphone.Start();
}
整体信号的幅度。您可以找到不在所有字节数组中的平均值,但在较小的窗口中可以获得幅度曲线:
private double GetSignalAmplitude(byte[] signal)
{
int BytesInSample = 2;
int signalSize = signal.Length / BytesInSample;
double Sum = 0.0;
for (int i = 0; i < signalSize; i++)
{
int sample = Math.Abs(BitConverter.ToInt16(signal, i * BytesInSample));
Sum += sample;
}
double amplitude = Sum / signalSize;
return amplitude;
}
用于即时生成声音的其他内容可能会帮助您:
DynamicSoundEffectInstance generatedSound = new DynamicSoundEffectInstance(SampleRate, AudioChannels.Mono);
generatedSound.SubmitBuffer(buffer);
private void Int16ToTwoBytes(byte[] output, Int16 value, int offset)
{
output[offset + 1] = (byte)(value >> 8);
output[offset] = (byte)(value & 0x00FF);
}