c# - 设置 MMDevice WaveFormat
问题描述
我正在尝试使用此代码设置用于录制音频设备“MMDevice”的 WaveFormat 我正在使用 NAudio:
// Getting The WaveFormat for the device
var value = selectedRecordingDevices.Properties[PropertyKeys.PKEY_AudioEngine_DeviceFormat].Value as byte[];
IntPtr unmanagedPointer = Marshal.AllocHGlobal(value.Length);
Marshal.Copy(value, 0, unmanagedPointer, value.Length);
Marshal.FreeHGlobal(unmanagedPointer);
var waveFormat = WaveFormat.MarshalFromPtr(unmanagedPointer);
// Setting The WaveFormat for the device
WaveFormat w = new WaveFormat(44100, 16, 2);
PropVariant p = new PropVariant();
p.pointerValue = WaveFormatToPointer(w);
selectedRecordingDevices.Properties.SetValue(PropertyKeys.PKEY_AudioEngine_DeviceFormat, p);
public static IntPtr WaveFormatToPointer(WaveFormat format)
{
IntPtr formatPointer = Marshal.AllocHGlobal(Marshal.SizeOf(format));
Marshal.StructureToPtr(format, formatPointer, false);
return formatPointer;
}
我得到了这个例外:
System.UnauthorizedAccessException
HResult=0x80070005
Message=Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
Source=NAudio
StackTrace:
at NAudio.CoreAudioApi.Interfaces.IPropertyStore.SetValue(PropertyKey& key, PropVariant& value)
at NAudio.CoreAudioApi.PropertyStore.SetValue(PropertyKey key, PropVariant value)
解决方案
1-在设置值之前,您需要设置 StorageAccessMode:
selectedRecordingDevice.GetPropertyInformation(StorageAccessMode.ReadWrite);
所以它看起来像这样:
// Setting The WaveFormat for the device
WaveFormat w = new WaveFormat(44100, 16, 2);
PropVariant p = new PropVariant();
p.pointerValue = WaveFormatToPointer(w);
selectedRecordingDevice.GetPropertyInformation(StorageAccessMode.ReadWrite);
selectedRecordingDevices.Properties.SetValue(PropertyKeys.PKEY_AudioEngine_DeviceFormat, p);
2-它必须以管理员身份运行
推荐阅读
- javascript - cropper.js - 意外的标识符
- angular - 路由器插座或路由在 angularjs7 中不起作用?
- python-3.x - 交叉验证时如何获得 AUC-ROC 而不是准确率?
- regex - Ensure specific characters are in a string, regardless of position, using a regex in Golang
- c++ - 带有invoke_result的重载命名非成员函数的返回类型
- .net - 在.net中使用语音识别时如何停止听写窗口?
- python - 如何在一行 html 前端中自动构建 3 个列卡
- android - 地址选择器 Android
- php - 邮递员请求:ImportError: cannot import name DEFAULT_CIPHERS
- python - 如何在 Python 中使用 Xades-EPES 标准进行签名?