我正在使用NAudio并尝试使用WasapiLoopbackCapture记录我在电脑上播放的内容。我遇到的问题是我需要记录的数据为PCM 16bit 44100khz Mono。 为此,我构建了这个:
using System;
using System.Diagnostics;
using NAudio.Wave;
using NAudio.CoreAudioApi;
namespace soundtest
{
class Program {
static void Main(string[] args) {
try {
var deviceToRecord = (new MMDeviceEnumerator().EnumerateAudioEndPoints(DataFlow.All, DeviceState.Active))[0];
var recorder = new CustomWasapiLoopbackCapture(deviceToRecord, false, 1000 / 5);
recorder.ShareMode = AudioClientShareMode.Shared;
recorder.DataAvailable += recorderDataAvailable;
var inprov = new WaveInProvider(recorder);
var fto16prov = new WaveFloatTo16Provider(inprov);
var stomprov = new StereoToMonoProvider16(fto16prov);
Console.WriteLine("Press something to stop recording.");
recorder.StartRecording();
Console.ReadKey();
recorder.StopRecording();
} catch (Exception e) {
Console.WriteLine("!!! EXCEPTION !!!" +
"\nMessage:\n " + e.Message +
"\nSource:\n " + e.Source +
"\nStack:\n" + e.StackTrace);
}
Console.WriteLine("Press something to close.");
Console.ReadKey();
}
static void recorderDataAvailable(object sender, WaveInEventArgs args) {
// how do I access PCM 16bit here?
// It's not args.Buffer, or am I wrong?
// additional calculation is done here with the PCM data
}
}
class CustomWasapiLoopbackCapture : WasapiCapture
{
public CustomWasapiLoopbackCapture()
: this(GetDefaultLoopbackCaptureDevice()){ }
public CustomWasapiLoopbackCapture(MMDevice captureDevice)
: this(captureDevice, false){ }
public CustomWasapiLoopbackCapture(MMDevice captureDevice, bool useEventSync)
: this(captureDevice, useEventSync, 100){ }
public CustomWasapiLoopbackCapture(MMDevice captureDevice, bool useEventSync, int audioBufferMillisecondsLength)
: base(captureDevice, useEventSync, audioBufferMillisecondsLength){ }
public static MMDevice GetDefaultLoopbackCaptureDevice() {
MMDeviceEnumerator devices = new MMDeviceEnumerator();
return devices.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
}
public override WaveFormat WaveFormat
{
get { return base.WaveFormat; }
set { throw new InvalidOperationException("WaveFormat cannot be set for WASAPI Loopback Capture"); }
}
protected override AudioClientStreamFlags GetAudioClientStreamFlags() {
return AudioClientStreamFlags.Loopback;
}
}
}
如何访问转换后的录音?我认为通过添加这些提供程序,我可以获得用于进一步计算的数据。我假设args.Buffer没有提供预期的PCM 16bit 44100 kHz Mono数据来自我在recorderDataAvailable方法中进行的额外处理的不切实际的结果。我用一个简单的WaveInEvent在我的调音台的另一个输入上测试了这个,我用它来播放播放的声音。
答案 0 :(得分:2)
WASAPI始终将音频记录为IEEE浮点样本。因此,在记录的缓冲区中,您将获得回调,每4个字节为float
。使用BitConverter.ToSingle
访问单个样本的简单方法。这将为您提供+/- 1.0范围内的值。因此,乘以32767,然后转换为Int16
,将其转换为16位样本值。