refactor: 声卡测试改用 NewLife.Audio 并移除 NAudio - A1Lib 音频设备/录音/梅尔分析切换到 NewLife.Audio:WASAPI 枚举、端点音量与混音格式,录音统一 48k/16bit 采集并按 16k 转存 - A2Lib 声卡选择与录音窗口适配新接口,测试播放改用 AudioPlayer,音量改用 AudioEndpointVolume - CrazyCoder 与 XCoder.App 声卡页接入 NewLife.Audio,Avalonia 版由占位改为真实枚举与测试播放 - 移除 A1Lib/CrazyCoder 的 NAudio 引用与 XCoder.App 冗余设备模型,NewLife.Audio 引入 1.3.2026.1113-beta1528大石头 authored at 2026-11-13 23:49:00
diff --git a/A1Lib/A1Lib.csproj b/A1Lib/A1Lib.csproj
index 82081ee..52fa4ff 100644
--- a/A1Lib/A1Lib.csproj
+++ b/A1Lib/A1Lib.csproj
@@ -17,7 +17,7 @@
<PackageReference Include="AForgeCore.Video" Version="1.0.0" />
<PackageReference Include="HidSharp" Version="2.6.4" />
<PackageReference Include="MathNet.Numerics" Version="5.0.0" />
- <PackageReference Include="NAudio" Version="2.3.0" />
+ <PackageReference Include="NewLife.Audio" Version="1.3.2026.1113-beta1528" />
<PackageReference Include="NewLife.Core" Version="12.0.2026.1109-beta0553" />
<PackageReference Include="System.IO.Ports" Version="10.0.15" />
<PackageReference Include="System.Management" Version="10.0.15" />
diff --git a/A1Lib/Audio/AudioDevice.cs b/A1Lib/Audio/AudioDevice.cs
index 3342ead..f2a5d15 100644
--- a/A1Lib/Audio/AudioDevice.cs
+++ b/A1Lib/Audio/AudioDevice.cs
@@ -1,10 +1,6 @@
-using NAudio.CoreAudioApi;
+using NewLife.Audio.Devices;
using NewLife.Collections;
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
namespace ALib.Audio
{
@@ -17,10 +13,10 @@ namespace ALib.Audio
public string ContainerId { get; set; }
/// <summary>播放设备</summary>
- public MMDevice PlaybackDevice;
+ public AudioDeviceInfo PlaybackDevice;
/// <summary>录音设备</summary>
- public MMDevice RecordingDevice;
+ public AudioDeviceInfo RecordingDevice;
#region
@@ -30,7 +26,7 @@ namespace ALib.Audio
public AudioRecord CreateWavRecord()
{
if (RecordingDevice == null) return null;
- if (RecordingDevice.AudioClient.MixFormat.Channels < 1) return null;
+ if (RecordingDevice.MixFormat != null && RecordingDevice.MixFormat.Channels < 1) return null;
return new AudioRecord(this);
}
@@ -45,64 +41,40 @@ namespace ALib.Audio
sb.AppendLine($"ContainerID:{ContainerId}");
sb.Append("播放:");
- if (PlaybackDevice != null)
+ var play = PlaybackDevice?.MixFormat;
+ if (play != null)
{
- sb.Append($" 声道:{PlaybackDevice.AudioClient.MixFormat.Channels}");
- sb.Append($" 采样率:{PlaybackDevice.AudioClient.MixFormat.SampleRate}");
+ sb.Append($" 声道:{play.Channels}");
+ sb.Append($" 采样率:{play.SampleRate}");
}
else
{
- sb.Append("无");
+ sb.Append(PlaybackDevice != null ? "有" : "无");
}
sb.AppendLine();
sb.Append("录音:");
- if (RecordingDevice != null)
+ var record = RecordingDevice?.MixFormat;
+ if (record != null)
{
- sb.Append($" 声道:{RecordingDevice.AudioClient.MixFormat.Channels}");
- sb.Append($" 采样率:{RecordingDevice.AudioClient.MixFormat.SampleRate}");
+ sb.Append($" 声道:{record.Channels}");
+ sb.Append($" 采样率:{record.SampleRate}");
}
else
{
- sb.Append("无");
+ sb.Append(RecordingDevice != null ? "有" : "无");
}
sb.AppendLine();
return sb.Return(true);
}
- /// <summary>字符串截取括号内内容</summary>
- /// <remarks>FriendlyName 中截取括号内声卡名称</remarks>
- /// <param name="str"></param>
- /// <returns></returns>
- private string getCardName(string str)
- {
- if (str == null) return null;
-
- int start = str.IndexOf('(') + 1;
- int end = str.IndexOf(')', start);
- if (start > 0 && end > start)
- {
- return str.Substring(start, end - start);
- }
-
- return null;
- }
-
/// <summary>获取声卡名称</summary>
/// <returns></returns>
public string GetCardName()
{
- if (PlaybackDevice != null)
- {
- return PlaybackDevice.DeviceFriendlyName;
- //return getCardName(PlaybackDevice.DeviceFriendlyName);
- }
- if (RecordingDevice != null)
- {
- return RecordingDevice.DeviceFriendlyName;
- //return getCardName(RecordingDevice.DeviceFriendlyName);
- }
+ if (PlaybackDevice != null) return PlaybackDevice.DeviceFriendlyName;
+ if (RecordingDevice != null) return RecordingDevice.DeviceFriendlyName;
return null;
}
}
diff --git a/A1Lib/Audio/AudioDeviceHelper.cs b/A1Lib/Audio/AudioDeviceHelper.cs
index 377489c..b705c2a 100644
--- a/A1Lib/Audio/AudioDeviceHelper.cs
+++ b/A1Lib/Audio/AudioDeviceHelper.cs
@@ -1,16 +1,7 @@
-using ALib.UsbHub;
+using ALib.UsbHub;
using Microsoft.Win32;
-using NAudio.CoreAudioApi;
using NewLife;
-using NewLife.Collections;
-using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Configuration;
-using System.Linq;
-using System.Runtime.CompilerServices;
-using System.Text;
-using System.Threading.Tasks;
+using NewLife.Audio.Devices;
namespace ALib.Audio
{
@@ -45,35 +36,24 @@ namespace ALib.Audio
public static Dictionary<string, AudioDevice> GetAudioDevices()
{
var dic = new Dictionary<string, AudioDevice>();
- var enumerator = new MMDeviceEnumerator();
- var playbackDevices = enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);
- var recordingDevices = enumerator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.Active);
+ if (!WasapiDriver.IsPlatformSupported) return dic;
- foreach (var dev in playbackDevices)
+ var devices = new WasapiDriver().EnumerateDevices();
+ foreach (var dev in devices)
{
- var containerId = GetAudioContainerID(dev.ID);
- if (containerId != null)
+ var containerId = GetAudioContainerID(dev.Id);
+ if (containerId == null) continue;
+
+ if (!dic.TryGetValue(containerId, out var audioDevice))
{
- if (!dic.TryGetValue(containerId, out var audioDevice))
- {
- audioDevice = new AudioDevice { ContainerId = containerId };
- dic[containerId] = audioDevice;
- }
- audioDevice.PlaybackDevice = dev;
+ audioDevice = new AudioDevice { ContainerId = containerId };
+ dic[containerId] = audioDevice;
}
- }
- foreach (var dev in recordingDevices)
- {
- var containerId = GetAudioContainerID(dev.ID);
- if (containerId != null)
- {
- if (!dic.TryGetValue(containerId, out var audioDevice))
- {
- audioDevice = new AudioDevice { ContainerId = containerId };
- dic[containerId] = audioDevice;
- }
+
+ if (dev.IsInput)
audioDevice.RecordingDevice = dev;
- }
+ else
+ audioDevice.PlaybackDevice = dev;
}
foreach (var item in dic)
diff --git a/A1Lib/Audio/AudioFeatureExtractor.cs b/A1Lib/Audio/AudioFeatureExtractor.cs
index 989cc3f..61787ba 100644
--- a/A1Lib/Audio/AudioFeatureExtractor.cs
+++ b/A1Lib/Audio/AudioFeatureExtractor.cs
@@ -1,6 +1,6 @@
using MathNet.Numerics;
using MathNet.Numerics.IntegralTransforms;
-using NAudio.Wave;
+using NewLife.Audio.DSP;
using System;
using System.Buffers;
using System.Collections.Generic;
@@ -99,7 +99,7 @@ namespace ALib.Audio
/// <summary>
/// 创建音频特征提取器实例,指定音频格式
/// </summary>
- public AudioFeatureExtractor(WaveFormat format, int melPoint = 30)
+ public AudioFeatureExtractor(AudioFormat format, int melPoint = 30)
{
SampleRate = format.SampleRate;
MelPointsPerSecond = melPoint;
diff --git a/A1Lib/Audio/AudioPreciseFreqDetector.cs b/A1Lib/Audio/AudioPreciseFreqDetector.cs
index fcd1757..4cb1fb6 100644
--- a/A1Lib/Audio/AudioPreciseFreqDetector.cs
+++ b/A1Lib/Audio/AudioPreciseFreqDetector.cs
@@ -1,6 +1,6 @@
using MathNet.Numerics;
using MathNet.Numerics.IntegralTransforms;
-using NAudio.Wave;
+using NewLife.Audio.DSP;
using System;
using System.Buffers;
using System.Collections.Generic;
@@ -97,7 +97,7 @@ namespace ALib.Audio
Initialize();
}
- public AudioPreciseFreqDetector(WaveFormat format, int pointsPerSecond = 30)
+ public AudioPreciseFreqDetector(AudioFormat format, int pointsPerSecond = 30)
{
SampleRate = format.SampleRate;
PointsPerSecond = pointsPerSecond;
diff --git a/A1Lib/Audio/AudioRecord.cs b/A1Lib/Audio/AudioRecord.cs
index 8451b24..091e3c1 100644
--- a/A1Lib/Audio/AudioRecord.cs
+++ b/A1Lib/Audio/AudioRecord.cs
@@ -1,13 +1,10 @@
-using NAudio.CoreAudioApi;
-using NAudio.Dmo;
-using NAudio.Wave;
+using NewLife;
+using NewLife.Audio.Containers;
+using NewLife.Audio.Devices;
+using NewLife.Audio.DSP;
using System;
-using System.Collections.Generic;
using System.IO;
-using System.Linq;
-using System.Text;
using System.Threading.Tasks;
-using NewLife;
namespace ALib.Audio
{
@@ -20,10 +17,10 @@ namespace ALib.Audio
#region 属性
/// <summary>存文件的wav格式,如果与设备录音格式不同,会自动转换为此格式</summary>
- public WaveFormat Format { get; set; }
+ public AudioFormat Format { get; set; }
/// <summary>设备实际录音格式</summary>
- public WaveFormat RecordFormat => _waveIn?.WaveFormat;
+ public AudioFormat RecordFormat => _waveIn?.Format;
/// <summary>是否正在录音</summary>
public bool IsRecording { get; private set; }
@@ -45,7 +42,7 @@ namespace ALib.Audio
public const long MaxMemorySize = 512L * 1024 * 1024;
/// <summary>录音采集器</summary>
- private WasapiCapture _waveIn;
+ private IAudioRecorder _waveIn;
/// <summary>内存流,用于存储录音原始数据</summary>
private MemoryStream _memoryStream;
@@ -68,20 +65,23 @@ namespace ALib.Audio
{
if (dev == null) throw new ArgumentNullException(nameof(dev));
if (dev.RecordingDevice == null) throw new ArgumentException(L.T("The recording device's RecordingDevice cannot be null."), nameof(dev));
- if (dev.RecordingDevice.AudioClient.MixFormat.Channels < 1)
+
+ // 设备混音格式的声道数决定采集声道数,缺省按立体声
+ var channels = dev.RecordingDevice.MixFormat?.Channels ?? 2;
+ if (channels < 1)
throw new ArgumentException(L.T("The recording device has an invalid channel count."), nameof(dev));
- // 使用 WasapiCapture 直接通过 MMDevice 录音
- _waveIn = new WasapiCapture(dev.RecordingDevice) { ShareMode = AudioClientShareMode.Shared };
+ // 使用 WASAPI 共享模式录音,统一请求 48kHz/16bit,设备格式差异由库内部转换
+ _waveIn = new WasapiDriver().CreateRecorder();
+ _waveIn.Init(new AudioFormat { SampleRate = 48000, Channels = channels, BitsPerSample = 16 }, dev.RecordingDevice.Id);
// 初始化内存流
_memoryStream = new MemoryStream();
// 注册事件
_waveIn.DataAvailable += OnDataAvailable;
- _waveIn.RecordingStopped += OnRecordingStopped;
- Format = new WaveFormat(16000, 16, RecordFormat.Channels);
+ Format = new AudioFormat { SampleRate = 16000, Channels = channels, BitsPerSample = 16 };
}
#endregion
@@ -112,11 +112,11 @@ namespace ALib.Audio
if (ms > 0)
{
_cts = new System.Threading.CancellationTokenSource();
- Task.Delay(ms, _cts.Token).ContinueWith(_ =>
+ var token = _cts.Token;
+ Task.Delay(ms, token).ContinueWith(t =>
{
- if (!_cts.Token.IsCancellationRequested)
- Stop();
- });
+ if (!t.IsCanceled) Stop();
+ }, TaskScheduler.Default);
}
return true;
@@ -143,6 +143,11 @@ namespace ALib.Audio
_waveIn.StopRecording();
}
catch (Exception) { }
+
+ IsRecording = false;
+
+ // 触发完成事件
+ OnRecordingStopped(this, EventArgs.Empty);
}
/// <summary>录音完成事件</summary>
@@ -189,40 +194,30 @@ namespace ALib.Audio
try
{
// 确定使用的格式:优先使用用户设定的 Format,否则使用实际录音格式
- var targetFormat = Format ?? _waveIn.WaveFormat;
+ var sourceFormat = _waveIn.Format;
+ var targetFormat = Format ?? sourceFormat;
+
+ // 声道或位深不一致时不做转换,按源格式写出,避免写出与实际数据不符的格式
+ var sameLayout = targetFormat.Channels == sourceFormat.Channels &&
+ targetFormat.BitsPerSample == sourceFormat.BitsPerSample &&
+ targetFormat.IsFloat == sourceFormat.IsFloat;
+ if (!sameLayout) targetFormat = sourceFormat;
string dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
Directory.CreateDirectory(dir);
- using var fs = new FileStream(path, FileMode.Create, FileAccess.Write);
- using var writer = new WaveFileWriter(fs, targetFormat);
-
// 将内存数据写入文件
var buffer = _memoryStream.ToArray();
- // 如果目标格式与录音格式一致,直接写入
- if (targetFormat.Encoding == _waveIn.WaveFormat.Encoding &&
- targetFormat.SampleRate == _waveIn.WaveFormat.SampleRate &&
- targetFormat.Channels == _waveIn.WaveFormat.Channels &&
- targetFormat.BitsPerSample == _waveIn.WaveFormat.BitsPerSample)
- {
- writer.Write(buffer, 0, buffer.Length);
- }
- else
- {
- // 需要转换格式:从内存流读取原始数据并重采样
- using var msCopy = new MemoryStream(buffer);
- using var reader = new RawWaveStream(msCopy, _waveIn.WaveFormat);
- using var resampler = new MediaFoundationResampler(reader, targetFormat);
-
- byte[] resampleBuffer = new byte[4096];
- int read;
- while ((read = resampler.Read(resampleBuffer, 0, resampleBuffer.Length)) > 0)
- {
- writer.Write(resampleBuffer, 0, read);
- }
- }
+ // 采样率不一致时重采样(16位整型 PCM)
+ if (targetFormat.SampleRate != sourceFormat.SampleRate && !sourceFormat.IsFloat && sourceFormat.BitsPerSample == 16)
+ buffer = Resampler.ResamplePcm(buffer, sourceFormat.SampleRate, targetFormat.SampleRate);
+
+ using var fs = new FileStream(path, FileMode.Create, FileAccess.Write);
+ using var writer = new WaveFileWriter(fs, targetFormat);
+ writer.WriteFrame(buffer);
+ writer.Flush();
return true;
}
@@ -238,7 +233,7 @@ namespace ALib.Audio
/// <returns>按照声道获取的音频数据,格式为 AudioFileReader 按照声道整理</returns>
public float[][] ReadAudioData(int length = -1)
{
- int channelCount = _waveIn?.WaveFormat?.Channels ?? 1;
+ int channelCount = _waveIn?.Format?.Channels ?? 1;
// 无数据时返回静音
if (_memoryStream == null || _memoryStream.Length == 0)
@@ -254,7 +249,7 @@ namespace ALib.Audio
return silence;
}
- var format = _waveIn.WaveFormat;
+ var format = _waveIn.Format;
int bytesPerSample = format.BitsPerSample / 8;
// 获取原始数据
@@ -281,7 +276,7 @@ namespace ALib.Audio
for (int ch = 0; ch < channelCount; ch++)
{
int byteIndex = i * bytesPerSample * channelCount + ch * bytesPerSample;
- if (format.Encoding == WaveFormatEncoding.IeeeFloat)
+ if (format.IsFloat)
{
channelBuffers[ch][i] = BitConverter.ToSingle(rawData, byteIndex);
}
@@ -306,7 +301,7 @@ namespace ALib.Audio
/// <returns>按照声道获取的音频数据,格式为 AudioFileReader 按照声道整理</returns>
public float[][] ReadAudioLastData(int length = -1)
{
- int channelCount = _waveIn?.WaveFormat?.Channels ?? 1;
+ int channelCount = _waveIn?.Format?.Channels ?? 1;
// 无数据时返回静音
if (_memoryStream == null || _memoryStream.Length == 0)
@@ -322,7 +317,7 @@ namespace ALib.Audio
return silence;
}
- var format = _waveIn.WaveFormat;
+ var format = _waveIn.Format;
int bytesPerSample = format.BitsPerSample / 8;
// 获取原始数据
@@ -351,7 +346,7 @@ namespace ALib.Audio
for (int ch = 0; ch < channelCount; ch++)
{
int srcByteIndex = (skipSamples + i) * bytesPerSample * channelCount + ch * bytesPerSample;
- if (format.Encoding == WaveFormatEncoding.IeeeFloat)
+ if (format.IsFloat)
{
channelBuffers[ch][destOffset + i] = BitConverter.ToSingle(rawData, srcByteIndex);
}
@@ -392,7 +387,7 @@ namespace ALib.Audio
/// <summary>给定时间算帧数</summary>
/// <param name="ms">毫秒</param>
/// <returns>音频帧数</returns>
- public int FramsFormTime(int ms) { return (int)(ms * _waveIn.WaveFormat.SampleRate / 1000); }
+ public int FramsFormTime(int ms) { return (int)(ms * _waveIn.Format.SampleRate / 1000); }
#endregion
@@ -424,27 +419,25 @@ namespace ALib.Audio
#region 内部事件处理
- private void OnDataAvailable(object sender, WaveInEventArgs e)
+ private void OnDataAvailable(object sender, byte[] e)
{
- if (e.BytesRecorded > 0)
+ var bytesRecorded = e?.Length ?? 0;
+ if (bytesRecorded > 0)
{
if (_IgnoreRemain > 0)
{
- var blen = e.BytesRecorded;
var format = RecordFormat;
- var fmlen = format.Channels;
- if (format.Encoding == WaveFormatEncoding.IeeeFloat) { fmlen *= 4; }
- else if (format.BitsPerSample == 16) { fmlen *= 2; }
- else if (format.BitsPerSample == 32) { fmlen *= 2; }
+ // 每帧字节数 = 声道数 × 每样本字节数
+ var fmlen = format.Channels * format.BytesPerSample;
// 本次帧个数
- var fmsize = blen / fmlen;
+ var fmsize = bytesRecorded / fmlen;
// 忽略掉的,可以多忽略一些,音频,无所谓。
_IgnoreRemain -= fmsize;
return;
}
// 检查内存限制
- if (_memoryStream.Length + e.BytesRecorded > MaxMemorySize)
+ if (_memoryStream.Length + bytesRecorded > MaxMemorySize)
{
// 标记为内存满停止
_stoppedByMemoryLimit = true;
@@ -458,25 +451,25 @@ namespace ALib.Audio
}
// 写入内存
- _memoryStream?.Write(e.Buffer, 0, e.BytesRecorded);
+ _memoryStream?.Write(e, 0, bytesRecorded);
// 计算并报告音量
if (VolumeUpdated != null)
{
- var vols = CalculateVolume(e.Buffer, e.BytesRecorded, _waveIn.WaveFormat);
+ var vols = CalculateVolume(e, bytesRecorded, _waveIn.Format);
VolumeUpdated?.Invoke(this, vols);
}
// 触发音频数据事件
if (DataUpdated != null)
{
- var audioData = ConvertToAudioData(e.Buffer, e.BytesRecorded, _waveIn.WaveFormat);
+ var audioData = ConvertToAudioData(e, bytesRecorded, _waveIn.Format);
DataUpdated?.Invoke(this, audioData);
}
}
}
- private void OnRecordingStopped(object sender, StoppedEventArgs e)
+ private void OnRecordingStopped(object sender, EventArgs e)
{
IsRecording = false;
@@ -491,7 +484,7 @@ namespace ALib.Audio
/// <param name="bytesRecorded">有效数据长度</param>
/// <param name="format">音频格式</param>
/// <returns>按声道组织的音频数据,第一维为声道索引</returns>
- private static float[][] ConvertToAudioData(byte[] buffer, int bytesRecorded, WaveFormat format)
+ private static float[][] ConvertToAudioData(byte[] buffer, int bytesRecorded, AudioFormat format)
{
if (format.Channels < 1 || buffer == null || bytesRecorded <= 0)
{
@@ -516,7 +509,7 @@ namespace ALib.Audio
for (int ch = 0; ch < channels; ch++)
{
int byteIndex = i * frameSize + ch * bytesPerSample;
- if (format.Encoding == WaveFormatEncoding.IeeeFloat)
+ if (format.IsFloat)
{
channelBuffers[ch][i] = BitConverter.ToSingle(buffer, byteIndex);
}
@@ -538,7 +531,7 @@ namespace ALib.Audio
/// 计算各声道音量
/// </summary>
/// <returns>各声道音量数组(0~100),长度等于声道数</returns>
- private static byte[] CalculateVolume(byte[] buffer, int bytesRecorded, WaveFormat format)
+ private static byte[] CalculateVolume(byte[] buffer, int bytesRecorded, AudioFormat format)
{
if (format.Channels < 1 || buffer == null || bytesRecorded <= 0)
{
@@ -560,7 +553,7 @@ namespace ALib.Audio
int byteIndex = i + ch * bytesPerSample;
float sampleValue = 0;
- if (format.Encoding == WaveFormatEncoding.IeeeFloat)
+ if (format.IsFloat)
{
sampleValue = Math.Abs(BitConverter.ToSingle(buffer, byteIndex));
}
@@ -603,10 +596,12 @@ namespace ALib.Audio
public void Dispose()
{
Stop();
- _waveIn.DataAvailable -= OnDataAvailable;
- _waveIn.RecordingStopped -= OnRecordingStopped;
- _waveIn?.Dispose();
- _waveIn = null;
+ if (_waveIn != null)
+ {
+ _waveIn.DataAvailable -= OnDataAvailable;
+ _waveIn.Dispose();
+ _waveIn = null;
+ }
_memoryStream?.Dispose();
_memoryStream = null;
_cts?.Dispose();
@@ -615,48 +610,4 @@ namespace ALib.Audio
#endregion
}
-
- #region 辅助类 - RawWaveStream
-
- /// <summary>
- /// 将原始 PCM 数据包装为 IWaveProvider,用于格式转换时的输入源
- /// </summary>
- internal class RawWaveStream : Stream, IWaveProvider
- {
- private readonly Stream _source;
- private readonly WaveFormat _waveFormat;
-
- public RawWaveStream(Stream source, WaveFormat format)
- {
- _source = source;
- _waveFormat = format;
- }
-
- public WaveFormat WaveFormat => _waveFormat;
-
- public override bool CanRead => true;
- public override bool CanSeek => _source.CanSeek;
- public override bool CanWrite => false;
- public override long Length => _source.Length;
- public override long Position
- {
- get => _source.Position;
- set => _source.Position = value;
- }
-
- public override void Flush() => _source.Flush();
- public override long Seek(long offset, SeekOrigin origin) => _source.Seek(offset, origin);
- public override void SetLength(long value) => _source.SetLength(value);
-
- public override int Read(byte[] buffer, int offset, int count) => _source.Read(buffer, offset, count);
- public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
-
- protected override void Dispose(bool disposing)
- {
- if (disposing) _source?.Dispose();
- base.Dispose(disposing);
- }
- }
-
- #endregion
}
diff --git a/A1Lib/Audio/MultiChannelAudioProcessor.cs b/A1Lib/Audio/MultiChannelAudioProcessor.cs
index f477445..1411cf2 100644
--- a/A1Lib/Audio/MultiChannelAudioProcessor.cs
+++ b/A1Lib/Audio/MultiChannelAudioProcessor.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -9,7 +9,7 @@ using System.Drawing.Imaging;
using System.Linq;
using MathNet.Numerics;
using MathNet.Numerics.IntegralTransforms;
-using NAudio.Wave;
+using NewLife.Audio;
using System.Numerics;
using System.Collections.Generic;
@@ -250,37 +250,35 @@ namespace ALib.Audio
private float[][] ReadAudioFile(string filePath)
{
- using (var audioFile = new AudioFileReader(filePath))
+ // 解码为 16 位小端交错 PCM,跨平台且不依赖系统解码器
+ var pcm = AudioFile.ReadPcm(filePath);
+ var format = pcm.Format;
+ SampleRate = format.SampleRate;
+
+ int channelCount = format.Channels;
+ var data = pcm.Data;
+ int bytesPerSample = 2;
+ int frameSize = bytesPerSample * channelCount;
+ int sampleCount = data.Length / frameSize;
+
+ // 为每个声道创建缓冲区
+ float[][] channelBuffers = new float[channelCount][];
+ for (int i = 0; i < channelCount; i++)
{
- // 获取参数
- int channelCount = audioFile.WaveFormat.Channels;
- int sampleRate = audioFile.WaveFormat.SampleRate;
- SampleRate = sampleRate;
-
- // 为每个声道创建缓冲区
- float[][] channelBuffers = new float[channelCount][];
- for (int i = 0; i < channelCount; i++)
- {
- channelBuffers[i] = new float[audioFile.Length / (4 * channelCount)]; // 每个float占4字节
- }
-
- // 临时缓冲区用于读取
- float[] interleavedBuffer = new float[audioFile.Length / 4];
- int samplesRead = audioFile.Read(interleavedBuffer, 0, interleavedBuffer.Length);
+ channelBuffers[i] = new float[sampleCount];
+ }
- // 解交错音频数据(多声道交错存储)
- for (int i = 0; i < samplesRead; i++)
+ // 解交错音频数据(多声道交错存储)
+ for (int i = 0; i < sampleCount; i++)
+ {
+ for (int ch = 0; ch < channelCount; ch++)
{
- int channel = i % channelCount;
- int position = i / channelCount;
- if (position < channelBuffers[channel].Length)
- {
- channelBuffers[channel][position] = interleavedBuffer[i];
- }
+ var value = BitConverter.ToInt16(data, i * frameSize + ch * bytesPerSample);
+ channelBuffers[ch][i] = value / 32768f;
}
-
- return channelBuffers;
}
+
+ return channelBuffers;
}
private double[][] CreateMelFilterBank()
diff --git a/A2Lib/Audio/AudioRecordForm.cs b/A2Lib/Audio/AudioRecordForm.cs
index 8bb6d34..c890478 100644
--- a/A2Lib/Audio/AudioRecordForm.cs
+++ b/A2Lib/Audio/AudioRecordForm.cs
@@ -1,6 +1,6 @@
-using ALib.Audio;
+using ALib.Audio;
using ALib.FormComponent;
-using NAudio.Wave;
+using NewLife.Audio.DSP;
using NewLife.Log;
using System.Drawing;
using NewLife;
@@ -84,7 +84,7 @@ namespace ALib.Audio
_recorder = new AudioRecord(SelectedDevice);
var recordFormat = _recorder.RecordFormat;
- WriteLog($"设备实际格式: {recordFormat.Encoding}, {recordFormat.SampleRate}Hz, {recordFormat.Channels}声道, {recordFormat.BitsPerSample}位");
+ WriteLog($"采集格式: {recordFormat.Encoding}, {recordFormat.SampleRate}Hz, {recordFormat.Channels}声道, {recordFormat.BitsPerSample}位");
WriteLog($"保存文件: {(cbSaveFile.Checked ? "是" : "否")}");
// 初始化梅尔特征提取器(按设备实际格式与声道数)
@@ -125,15 +125,16 @@ namespace ALib.Audio
/// <summary>音量更新回调</summary>
private void OnVolumeUpdated(Object sender, byte[] vols)
{
- _leftVolume = vols[0];
- _rightVolume = vols[1];
+ // 单声道设备只有一路音量,右声道复用左声道
+ _leftVolume = vols != null && vols.Length > 0 ? vols[0] : 0;
+ _rightVolume = vols != null && vols.Length > 1 ? vols[1] : _leftVolume;
this.UpdateUIControl(UpdateVolumeDisplay);
}
/// <summary>创建梅尔特征提取器</summary>
/// <param name="format">设备录音格式</param>
- private void CreateMelExtractors(WaveFormat format)
+ private void CreateMelExtractors(AudioFormat format)
{
if (format == null) return;
diff --git a/A2Lib/Audio/AudioSelect.cs b/A2Lib/Audio/AudioSelect.cs
index 5f72251..fca305f 100644
--- a/A2Lib/Audio/AudioSelect.cs
+++ b/A2Lib/Audio/AudioSelect.cs
@@ -1,14 +1,14 @@
-using ALib.Audio;
-using NAudio.CoreAudioApi;
-using NAudio.Utils;
-using NAudio.Wave;
+using ALib.Audio;
using NewLife;
+using NewLife.Audio;
+using NewLife.Audio.Devices;
using NewLife.Log;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
+using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -64,12 +64,10 @@ namespace ALib.Audio
var dev = Devices[cid];
rtb_Info.Text = dev.ToString();
- // 需要有播放和录音设备,且至少是立体声,才能启用确定按钮
+ // 需要有播放和录音设备,才能启用确定按钮
bool en = true;
if (dev.PlaybackDevice == null) en = false;
if (dev.RecordingDevice == null) en = false;
- if (dev.PlaybackDevice?.AudioClient.MixFormat.Channels < 2) en = false;
- if (dev.RecordingDevice?.AudioClient.MixFormat.Channels < 2) en = false;
btn_ok.Enabled = en;
// 如果有播放设备,启用测试按钮
@@ -92,26 +90,49 @@ namespace ALib.Audio
var cid = cb_Dev.SelectedItem as String;
if (cid.IsNullOrEmpty()) return;
var dev = Devices[cid];
+ if (dev.PlaybackDevice == null) return;
- // 设置音量
- dev.PlaybackDevice.AudioEndpointVolume.MasterVolumeLevelScalar = tb_Volume.Value * 0.02f;
- // 确保未静音
- dev.PlaybackDevice.AudioEndpointVolume.Mute = false;
-
- // 指定声卡播放测试音频
- // var af = new AudioFileReader(@"playTest.wav");
- var af = new WaveFileReader(new MemoryStream(ALib.Properties.Resources.playTest));
- // af.TotalTime;
- var waveOut = new WasapiOut(dev.PlaybackDevice, AudioClientShareMode.Shared, false, 100);
- waveOut.Init(af);
- waveOut.PlaybackStopped += (s, a) =>
+ // 设置端点音量并确保未静音(等同系统音量合成器对该设备的调整)
+ AudioEndpointVolume endpointVolume = null;
+ if (AudioEndpointVolume.IsSupported)
{
- af.Dispose();
- waveOut.Dispose();
- this.Invoke(() => { btn_Spk.Enabled = true; });
- };
+ try
+ {
+ endpointVolume = AudioEndpointVolume.Open(dev.PlaybackDevice.Id);
+ endpointVolume.Volume = tb_Volume.Value * 0.02f;
+ endpointVolume.Mute = false;
+ }
+ catch (Exception ex)
+ {
+ WriteLog("设置端点音量失败: {0}", ex.Message);
+ }
+ }
+
btn_Spk.Enabled = false;
- waveOut.Play();
+
+ // 指定声卡播放测试音频,播放较慢不阻塞界面
+ Task.Run(() =>
+ {
+ try
+ {
+ using var player = new AudioPlayer(deviceId: dev.PlaybackDevice.Id);
+ using var ms = new MemoryStream(ALib.Properties.Resources.playTest);
+ player.Play(ms);
+ }
+ catch (Exception ex)
+ {
+ WriteLog("播放测试音频失败: {0}", ex.Message);
+ }
+ finally
+ {
+ endpointVolume?.Dispose();
+ try
+ {
+ if (!IsDisposed && IsHandleCreated) this.Invoke(() => { btn_Spk.Enabled = true; });
+ }
+ catch (Exception) { }
+ }
+ });
}
#region 日志
diff --git a/A2Lib/ComPort/ComForm.cs b/A2Lib/ComPort/ComForm.cs
index f44fb96..df002aa 100644
--- a/A2Lib/ComPort/ComForm.cs
+++ b/A2Lib/ComPort/ComForm.cs
@@ -1,5 +1,4 @@
-using ALib.ComPort;
-using NAudio.Mixer;
+using ALib.ComPort;
using NewLife;
using NewLife.Data;
using NewLife.Net;
diff --git a/CrazyCoder/CoderWpf.csproj b/CrazyCoder/CoderWpf.csproj
index e07a55d..ef38a60 100644
--- a/CrazyCoder/CoderWpf.csproj
+++ b/CrazyCoder/CoderWpf.csproj
@@ -39,7 +39,7 @@
<PackageReference Include="NewLife.Redis" Version="7.0.2026.1026-beta0931" />
<PackageReference Include="NewLife.Map" Version="2.8.2026.1024" />
<PackageReference Include="NewLife.ModbusRTU" Version="2.1.2026.1024" />
- <PackageReference Include="NAudio" Version="2.4.0" />
+ <PackageReference Include="NewLife.Audio" Version="1.3.2026.1113-beta1528" />
<PackageReference Include="SSH.NET" Version="2026.0.0" />
<PackageReference Include="System.IO.Ports" Version="10.0.15" />
<PackageReference Include="System.Speech" Version="10.0.15" />
diff --git a/CrazyCoder/ViewModels/AudioDeviceViewModel.cs b/CrazyCoder/ViewModels/AudioDeviceViewModel.cs
index 620e2e7..84cc5a2 100644
--- a/CrazyCoder/ViewModels/AudioDeviceViewModel.cs
+++ b/CrazyCoder/ViewModels/AudioDeviceViewModel.cs
@@ -2,39 +2,13 @@ using System.Collections.ObjectModel;
using System.Text;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
-using NAudio.CoreAudioApi;
using NewLife;
+using NewLife.Audio;
+using NewLife.Audio.Devices;
+using NewLife.Audio.DSP;
namespace CrazyCoder.ViewModels;
-/// <summary>音频设备信息</summary>
-public class AudioDeviceInfo
-{
- /// <summary>设备 ID</summary>
- public String Id { get; set; } = "";
-
- /// <summary>设备名称</summary>
- public String Name { get; set; } = "";
-
- /// <summary>设备友好名称</summary>
- public String FriendlyName { get; set; } = "";
-
- /// <summary>声道数</summary>
- public Int32 Channels { get; set; }
-
- /// <summary>采样率</summary>
- public Int32 SampleRate { get; set; }
-
- /// <summary>是否有播放功能</summary>
- public Boolean HasPlayback { get; set; }
-
- /// <summary>是否有录音功能</summary>
- public Boolean HasRecording { get; set; }
-
- /// <summary>音量</summary>
- public Single Volume { get; set; } = 0.5f;
-}
-
/// <summary>声卡选择器 ViewModel</summary>
public partial class AudioDeviceViewModel : ObservableObject
{
@@ -58,8 +32,8 @@ public partial class AudioDeviceViewModel : ObservableObject
[ObservableProperty]
private String _log = "";
- private MMDeviceEnumerator _enumerator;
- private Dictionary<String, AudioDeviceInfo> _devices = [];
+ private readonly List<AudioDeviceInfo> _devices = [];
+ private Boolean _updatingVolume;
#endregion
#region 构造
@@ -68,7 +42,6 @@ public partial class AudioDeviceViewModel : ObservableObject
{
try
{
- _enumerator = new MMDeviceEnumerator();
RefreshDevices();
}
catch (Exception ex)
@@ -88,60 +61,21 @@ public partial class AudioDeviceViewModel : ObservableObject
try
{
- // 枚举播放设备
- var playbackDevices = _enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);
- foreach (var dev in playbackDevices)
+ if (!WasapiDriver.IsPlatformSupported)
{
- var id = dev.ID;
- if (!_devices.ContainsKey(id))
- {
- _devices[id] = new AudioDeviceInfo
- {
- Id = id,
- Name = dev.FriendlyName,
- FriendlyName = dev.DeviceFriendlyName,
- HasPlayback = true,
- Channels = dev.AudioClient.MixFormat.Channels,
- SampleRate = dev.AudioClient.MixFormat.SampleRate,
- };
- }
- else
- {
- _devices[id].HasPlayback = true;
- }
+ AppendLog("当前平台不支持 WASAPI 音频设备");
+ return;
}
- // 枚举录音设备
- var recordingDevices = _enumerator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.Active);
- foreach (var dev in recordingDevices)
+ foreach (var dev in new WasapiDriver().EnumerateDevices())
{
- var id = dev.ID;
- if (!_devices.ContainsKey(id))
- {
- _devices[id] = new AudioDeviceInfo
- {
- Id = id,
- Name = dev.FriendlyName,
- FriendlyName = dev.DeviceFriendlyName,
- HasRecording = true,
- Channels = dev.AudioClient.MixFormat.Channels,
- SampleRate = dev.AudioClient.MixFormat.SampleRate,
- };
- }
- else
- {
- _devices[id].HasRecording = true;
- }
- }
-
- foreach (var kv in _devices)
- {
- DeviceList.Add(kv.Value.Name);
+ _devices.Add(dev);
+ DeviceList.Add($"{dev.Name}({(dev.IsInput ? "录音" : "播放")})");
}
if (DeviceList.Count > 0) SelectedDeviceIndex = 0;
- AppendLog($"刷新完成,找到 {_devices.Count} 个音频设备");
+ AppendLog($"刷新完成,找到 {_devices.Count} 个音频端点");
}
catch (Exception ex)
{
@@ -151,30 +85,120 @@ public partial class AudioDeviceViewModel : ObservableObject
partial void OnSelectedDeviceIndexChanged(Int32 value)
{
- if (value < 0 || value >= DeviceList.Count) return;
-
- var name = DeviceList[value];
- var dev = _devices.Values.FirstOrDefault(d => d.Name == name);
- if (dev == null) return;
+ if (value < 0 || value >= _devices.Count) return;
+ var dev = _devices[value];
var sb = new StringBuilder();
sb.AppendLine($"设备: {dev.Name}");
- sb.AppendLine($"友好名称: {dev.FriendlyName}");
- sb.AppendLine($"播放: {(dev.HasPlayback ? "是" : "否")}");
- sb.AppendLine($"录音: {(dev.HasRecording ? "是" : "否")}");
- sb.AppendLine($"声道数: {dev.Channels}");
- sb.AppendLine($"采样率: {dev.SampleRate} Hz");
+ sb.AppendLine($"接口: {dev.DeviceFriendlyName}");
+ sb.AppendLine($"方向: {(dev.IsInput ? "录音" : "播放")}");
+ sb.AppendLine($"默认设备: {(dev.IsDefault ? "是" : "否")}");
+ var fmt = dev.MixFormat;
+ if (fmt != null)
+ {
+ sb.AppendLine($"声道数: {fmt.Channels}");
+ sb.AppendLine($"采样率: {fmt.SampleRate} Hz");
+ sb.AppendLine($"位深: {fmt.BitsPerSample} 位{(fmt.IsFloat ? "(浮点)" : "")}");
+ }
+ sb.AppendLine($"设备 ID: {dev.Id}");
DeviceDetail = sb.ToString();
- VolumeValue = dev.Volume * 100;
+
+ // 同步端点音量
+ _updatingVolume = true;
+ try
+ {
+ using var volume = AudioEndpointVolume.Open(dev.Id);
+ VolumeValue = volume.Volume * 100;
+ }
+ catch (Exception ex)
+ {
+ AppendLog($"读取端点音量失败: {ex.Message}");
+ }
+ finally
+ {
+ _updatingVolume = false;
+ }
+ }
+
+ partial void OnVolumeValueChanged(Double value)
+ {
+ if (_updatingVolume) return;
+ if (SelectedDeviceIndex < 0 || SelectedDeviceIndex >= _devices.Count) return;
+
+ var dev = _devices[SelectedDeviceIndex];
+ try
+ {
+ using var volume = AudioEndpointVolume.Open(dev.Id);
+ volume.Volume = (Single)(value / 100);
+ volume.Mute = false;
+ }
+ catch (Exception ex)
+ {
+ AppendLog($"设置端点音量失败: {ex.Message}");
+ }
}
/// <summary>测试播放</summary>
[RelayCommand]
private void TestPlayback()
{
- // NAudio 播放测试需要额外实现,这里简化处理
- AppendLog("播放测试功能需要在 View 层实现");
+ if (SelectedDeviceIndex < 0 || SelectedDeviceIndex >= _devices.Count) return;
+
+ var dev = _devices[SelectedDeviceIndex];
+ if (dev.IsInput)
+ {
+ AppendLog("录音端点不能用于播放");
+ return;
+ }
+
+ try
+ {
+ using var volume = AudioEndpointVolume.Open(dev.Id);
+ volume.Volume = (Single)(VolumeValue / 100);
+ volume.Mute = false;
+ }
+ catch (Exception ex)
+ {
+ AppendLog($"设置端点音量失败: {ex.Message}");
+ }
+
+ var pcm = BuildTone();
+ AppendLog($"开始播放测试音: {dev.Name}");
+
+ // 播放阻塞到播完,放到后台线程避免卡界面
+ Task.Run(() =>
+ {
+ try
+ {
+ using var player = new AudioPlayer(deviceId: dev.Id);
+ player.Play(pcm);
+ AppendLog("测试播放完成");
+ }
+ catch (Exception ex)
+ {
+ AppendLog($"测试播放失败: {ex.Message}");
+ }
+ });
+ }
+
+ /// <summary>生成 1 秒 440Hz 立体声 16 位 PCM 测试音</summary>
+ private static AudioPcm BuildTone()
+ {
+ var format = new AudioFormat { SampleRate = 48000, Channels = 2, BitsPerSample = 16 };
+ var frames = format.SampleRate;
+ var data = new Byte[frames * format.Channels * 2];
+ for (var i = 0; i < frames; i++)
+ {
+ var v = (Int16)(6000 * Math.Sin(2 * Math.PI * 440 * i / format.SampleRate));
+ for (var c = 0; c < format.Channels; c++)
+ {
+ data[(i * format.Channels + c) * 2] = (Byte)(v & 0xFF);
+ data[(i * format.Channels + c) * 2 + 1] = (Byte)((v >> 8) & 0xFF);
+ }
+ }
+
+ return new AudioPcm { Format = format, Data = data };
}
private void AppendLog(String msg)
@@ -182,4 +206,4 @@ public partial class AudioDeviceViewModel : ObservableObject
Log += $"{msg}\r\n";
}
#endregion
-}
+}
\ No newline at end of file
diff --git a/CrazyCoder/ViewModels/MelSpectrumViewModel.cs b/CrazyCoder/ViewModels/MelSpectrumViewModel.cs
index d273251..ee1c787 100644
--- a/CrazyCoder/ViewModels/MelSpectrumViewModel.cs
+++ b/CrazyCoder/ViewModels/MelSpectrumViewModel.cs
@@ -4,6 +4,7 @@ using System.IO;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using NewLife;
+using NewLife.Audio;
namespace CrazyCoder.ViewModels;
@@ -64,27 +65,30 @@ public partial class MelSpectrumViewModel : ObservableObject
{
Log += $"正在处理: {value}\r\n";
- // 使用 NAudio 读取 WAV 文件
- using var reader = new NAudio.Wave.AudioFileReader(value);
- var channels = reader.WaveFormat.Channels;
- var sampleRate = reader.WaveFormat.SampleRate;
- var bitsPerSample = reader.WaveFormat.BitsPerSample;
+ // 使用 NewLife.Audio 解码为 16 位 PCM,跨平台且不依赖系统解码器
+ var pcm = AudioFile.ReadPcm(value);
+ var channels = pcm.Format.Channels;
+ var sampleRate = pcm.Format.SampleRate;
+ var bitsPerSample = pcm.Format.BitsPerSample;
Log += $"声道数: {channels}, 采样率: {sampleRate}, 位深: {bitsPerSample}\r\n";
- var totalSamples = (Int32)(reader.Length / (bitsPerSample / 8));
+ var data = pcm.Data;
+ var totalSamples = data.Length / 2;
var samplesPerChannel = totalSamples / channels;
-
- // 读取所有样本
- var allSamples = new Single[totalSamples];
- var read = reader.Read(allSamples, 0, totalSamples);
-
- if (read == 0)
+ if (totalSamples == 0)
{
Log += "未能读取音频数据\r\n";
return;
}
+ // 读取所有样本为 [-1,1] 的浮点
+ var allSamples = new Single[totalSamples];
+ for (var i = 0; i < totalSamples; i++)
+ {
+ allSamples[i] = BitConverter.ToInt16(data, i * 2) / 32768f;
+ }
+
// 为每个声道生成频谱
for (var ch = 0; ch < channels; ch++)
{
diff --git "a/Doc/\345\212\237\350\203\275\346\270\205\345\215\225.md" "b/Doc/\345\212\237\350\203\275\346\270\205\345\215\225.md"
index 4f8f18f..a5e5031 100644
--- "a/Doc/\345\212\237\350\203\275\346\270\205\345\215\225.md"
+++ "b/Doc/\345\212\237\350\203\275\346\270\205\345\215\225.md"
@@ -134,7 +134,7 @@
| IND-6a | USB 设备(Windows,WMI) | 适配器 | ✅ | ✅ | ✅ | 平台诊断页枚举(CIM JSON 解析)+ 旧窗口均可用;实测非空 |
| IND-6b | USB 设备(Linux,sysfs) | 适配器 | ✅ | ✅ | ✅ | sysfs 枚举实现 + 解析单测;平台诊断页可直接看结果 |
| IND-6c | USB 设备(macOS,system_profiler) | 适配器 | ✅ | ✅ | ✅ | system_profiler 枚举 + 解析单测;未在 Mac 真机验证
-| IND-7a | 声卡测试(Windows,WASAPI) | 适配器 | ✅ | ✅ | ✅ | 平台诊断页枚举(Win32_SoundDevice)+ 旧窗口录音回放均可用 |
+| IND-7a | 声卡测试(Windows,WASAPI) | 适配器 | ✅ | ✅ | ✅ | 平台诊断页枚举(Win32_SoundDevice)+ 旧窗口录音回放均可用;音频链路统一走 NewLife.Audio(WASAPI 枚举/采集/播放、端点音量与混音格式),NAudio 依赖已移除 |
| IND-7b | 声卡测试(Linux,ALSA/PulseAudio) | 适配器 | ✅ | ✅ | ✅ | arecord 枚举 + 解析单测;录音播放需真实 ALSA 环境
| IND-7c | 声卡测试(macOS,CoreAudio) | 适配器 | ✅ | ✅ | ✅ | system_profiler SPAudioDataType 枚举 + 解析单测;未在 Mac 真机验证 |
| IND-8a | IP 设置(Windows,netsh) | 适配器 | ✅ | ✅ | ✅ | 旧窗口 + 平台诊断页命令生成/执行均可用(netsh 实测) |
@@ -174,7 +174,7 @@
| EFF-7a | 语音助手(Windows,SAPI) | 适配器 | ✅ | ✅ | ✅ | PowerShell + SAPI 执行朗读,支持音色/语速/音量与导出 WAV(实测生成 PCM16 单声道 WAV);11 项单测 |
| EFF-7b | 语音助手(Linux,espeak) | 适配器 | ✅ | ✅ | ✅ | espeak 命令构建+转义+执行路径完成;缺依赖时提示安装 espeak-ng |
| EFF-7c | 语音助手(macOS,say) | 适配器 | ✅ | ✅ | ✅ | say 命令构建+音色参数+导出音频执行路径完成 |
-| EFF-8 | 梅尔频谱(采集、计算、可视化) | 前端+逻辑 | ✅ | ✅ | ✅ | 纯托管实现(不依赖 NAudio,三平台一致):RIFF/WAVE 8/16/24/32 位与 float32 解码、基 2 FFT、梅尔滤波器组、对数梅尔谱 + 音量曲线 + CSV 导出;17 项单测 |
+| EFF-8 | 梅尔频谱(采集、计算、可视化) | 前端+逻辑 | ✅ | ✅ | ✅ | 纯托管实现(不依赖第三方音频库,三平台一致):RIFF/WAVE 8/16/24/32 位与 float32 解码、基 2 FFT、梅尔滤波器组、对数梅尔谱 + 音量曲线 + CSV 导出;17 项单测 |
> 父需求状态:❌
@@ -268,7 +268,7 @@
| Inno Setup / linuxdeploy / fpm / 签名公证(OPS-5/6/7 余项) | `tools/` | 环境依赖:本机无对应工具链与证书。**已补** `tools/pack-deb.sh`(dpkg-deb 手打,无需 fpm/联网)并在 WSL 实测安装可用;Inno Setup、AppImage、rpm、DMG 与 loongarch64 仍需工具链到位后实跑 |
| Linux / macOS / LoongArch 真机验证(OPS-3/4、IND-1b/6/7/8) | 平台适配层 | **Linux 已用 WSL 实测**(USB sysfs / ip / arecord / SocketCAN / 串口 / RTU / Redis / SSH);macOS 与 LoongArch 无真机,代码路径与解析单测就绪 |
| 真实硬件联调(CAN 厂商 DLL、Modbus 设备、局域网 API 广播) | IND-1a/1c、NET-5、DEV-5 | 环境依赖:ZLG/PCAN 厂商 DLL 与 macOS 驱动需硬件;Modbus 已用本机从站回环实测,API 发现已支持目标 IP 点对点探测。串口/RTU/Redis/SSH 已在 WSL 真实验证(见上) |
-| 实时录音采集(EFF-8 余项) | `ViewModels/MelSpectrumViewModel.cs` | 暂缓:需平台音频采集依赖;当前支持文件导入 → 频谱计算 → CSV 导出 |
+| 实时录音采集(EFF-8 余项) | `ViewModels/MelSpectrumViewModel.cs` | 依赖已具备:声卡链路统一到 NewLife.Audio 后可直接采集;当前仍只做文件导入 → 频谱计算 → CSV 导出,实时采集待排期 |
| 本地语音试听(NET-8)的 Linux/macOS 分支 | `Tools/Voice/SpeechCommandBuilder.cs` | 已验 Windows SAPI 真实合成(导出 WAV);Linux espeak-ng / macOS say 命令已就绪但本机无引擎,属环境依赖 |
---
diff --git "a/Doc/\346\236\266\346\236\204\350\256\276\350\256\241.md" "b/Doc/\346\236\266\346\236\204\350\256\276\350\256\241.md"
index 81387c4..eeb7b8e 100644
--- "a/Doc/\346\236\266\346\236\204\350\256\276\350\256\241.md"
+++ "b/Doc/\346\236\266\346\236\204\350\256\276\350\256\241.md"
@@ -249,7 +249,7 @@ Linux 专属能力(SocketCAN、串口、ALSA、sysfs)不必等真机,可
- **能力声明**:`ToolDescriptor.Platforms` 与运行时探测双重过滤;不可用的工具在首页置灰并给出原因,不隐藏到用户找不到。LoongArch 新世界复用 Linux 实现;QEMU 用于 CI 冒烟,硬件能力以龙芯真机验收为准,未验收的工具由运行时探测置灰。
- **macOS 验证边界**:Mac 真机已确认可获取;CI 负责签名/公证,真机负责串口/CAN/音频/USB/输入法等硬件能力验收;未验收前按能力矩阵置灰。
- **降级策略**:只读可用时降级为只读,并在状态栏说明;不可用时按钮禁用 + 提示文案。
-- **音频优先复用 `NewLife.Audio`**(跨平台设备 I/O 与 DSP),不足时再落平台实现。
+- **音频优先复用 `NewLife.Audio`**(跨平台设备 I/O 与 DSP),不足时再落平台实现;缺口已在 NewLife.Audio 侧补齐(端点音量、混音格式),NAudio 依赖已全部移除。
---
diff --git a/XCoder.App/ViewModels/AudioDeviceViewModel.cs b/XCoder.App/ViewModels/AudioDeviceViewModel.cs
index 290b564..f72c7b4 100644
--- a/XCoder.App/ViewModels/AudioDeviceViewModel.cs
+++ b/XCoder.App/ViewModels/AudioDeviceViewModel.cs
@@ -3,7 +3,9 @@ using System.Text;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using NewLife;
-using NewLife.XCoder.Models;
+using NewLife.Audio;
+using NewLife.Audio.Devices;
+using NewLife.Audio.DSP;
namespace NewLife.XCoder.ViewModels;
@@ -30,16 +32,23 @@ public partial class AudioDeviceViewModel : ObservableObject
[ObservableProperty]
private String _log = "";
- private Dictionary<String, AudioDeviceInfo> _devices = [];
+ private readonly List<AudioDeviceInfo> _devices = [];
+ private IAudioDriver? _driver;
+ private Boolean _updatingVolume;
#endregion
#region 构造
/// <summary>实例化声卡选择器 ViewModel</summary>
public AudioDeviceViewModel()
{
- // NAudio 在 Avalonia 跨平台不可用,显示友好提示
- AppendLog("声卡选择器在跨平台环境下使用简化功能。");
- AppendLog("完整功能需要 NAudio 库(仅支持 Windows)。");
+ try
+ {
+ RefreshDevices();
+ }
+ catch (Exception ex)
+ {
+ AppendLog($"初始化音频设备失败: {ex.Message}");
+ }
}
#endregion
@@ -53,8 +62,21 @@ public partial class AudioDeviceViewModel : ObservableObject
try
{
- // 跨平台兼容:使用简化设备枚举
- AppendLog("刷新设备功能在跨平台环境下受限。");
+ var driver = GetDriver();
+ foreach (var dev in driver.EnumerateDevices())
+ {
+ _devices.Add(dev);
+ DeviceList.Add($"{dev.Name}({(dev.IsInput ? "录音" : "播放")})");
+ }
+
+ if (DeviceList.Count > 0) SelectedDeviceIndex = 0;
+
+ if (_devices.Count == 0)
+ AppendLog(WasapiDriver.IsPlatformSupported
+ ? "未找到音频设备"
+ : "当前平台暂不支持音频设备枚举");
+ else
+ AppendLog($"刷新完成,找到 {_devices.Count} 个音频端点");
}
catch (Exception ex)
{
@@ -64,30 +86,130 @@ public partial class AudioDeviceViewModel : ObservableObject
partial void OnSelectedDeviceIndexChanged(Int32 value)
{
- if (value < 0 || value >= DeviceList.Count) return;
-
- var name = DeviceList[value];
- if (!_devices.TryGetValue(name, out var dev)) return;
+ if (value < 0 || value >= _devices.Count) return;
+ var dev = _devices[value];
var sb = new StringBuilder();
sb.AppendLine($"设备: {dev.Name}");
- sb.AppendLine($"友好名称: {dev.FriendlyName}");
- sb.AppendLine($"播放: {(dev.HasPlayback ? "是" : "否")}");
- sb.AppendLine($"录音: {(dev.HasRecording ? "是" : "否")}");
- sb.AppendLine($"声道数: {dev.Channels}");
- sb.AppendLine($"采样率: {dev.SampleRate} Hz");
+ sb.AppendLine($"接口: {dev.DeviceFriendlyName}");
+ sb.AppendLine($"方向: {(dev.IsInput ? "录音" : "播放")}");
+ sb.AppendLine($"默认设备: {(dev.IsDefault ? "是" : "否")}");
+ var fmt = dev.MixFormat;
+ if (fmt != null)
+ {
+ sb.AppendLine($"声道数: {fmt.Channels}");
+ sb.AppendLine($"采样率: {fmt.SampleRate} Hz");
+ sb.AppendLine($"位深: {fmt.BitsPerSample} 位{(fmt.IsFloat ? "(浮点)" : "")}");
+ }
+ sb.AppendLine($"设备 ID: {dev.Id}");
DeviceDetail = sb.ToString();
- VolumeValue = dev.Volume * 100;
+
+ // 同步端点音量(仅 Windows WASAPI 支持)
+ if (!AudioEndpointVolume.IsSupported) return;
+
+ _updatingVolume = true;
+ try
+ {
+ using var volume = AudioEndpointVolume.Open(dev.Id);
+ VolumeValue = volume.Volume * 100;
+ }
+ catch (Exception ex)
+ {
+ AppendLog($"读取端点音量失败: {ex.Message}");
+ }
+ finally
+ {
+ _updatingVolume = false;
+ }
+ }
+
+ partial void OnVolumeValueChanged(Double value)
+ {
+ if (_updatingVolume || !AudioEndpointVolume.IsSupported) return;
+ if (SelectedDeviceIndex < 0 || SelectedDeviceIndex >= _devices.Count) return;
+
+ var dev = _devices[SelectedDeviceIndex];
+ try
+ {
+ using var volume = AudioEndpointVolume.Open(dev.Id);
+ volume.Volume = (Single)(value / 100);
+ volume.Mute = false;
+ }
+ catch (Exception ex)
+ {
+ AppendLog($"设置端点音量失败: {ex.Message}");
+ }
}
/// <summary>测试播放</summary>
[RelayCommand]
private void TestPlayback()
{
- AppendLog("播放测试功能在跨平台环境受限。");
+ if (SelectedDeviceIndex < 0 || SelectedDeviceIndex >= _devices.Count) return;
+
+ var dev = _devices[SelectedDeviceIndex];
+ if (dev.IsInput)
+ {
+ AppendLog("录音端点不能用于播放");
+ return;
+ }
+
+ if (AudioEndpointVolume.IsSupported)
+ {
+ try
+ {
+ using var volume = AudioEndpointVolume.Open(dev.Id);
+ volume.Volume = (Single)(VolumeValue / 100);
+ volume.Mute = false;
+ }
+ catch (Exception ex)
+ {
+ AppendLog($"设置端点音量失败: {ex.Message}");
+ }
+ }
+
+ var pcm = BuildTone();
+ AppendLog($"开始播放测试音: {dev.Name}");
+
+ // 播放阻塞到播完,放到后台线程避免卡界面
+ Task.Run(() =>
+ {
+ try
+ {
+ using var player = new AudioPlayer(GetDriver(), dev.Id);
+ player.Play(pcm);
+ AppendLog("测试播放完成");
+ }
+ catch (Exception ex)
+ {
+ AppendLog($"测试播放失败: {ex.Message}");
+ }
+ });
+ }
+
+ /// <summary>生成 1 秒 440Hz 立体声 16 位 PCM 测试音</summary>
+ private static AudioPcm BuildTone()
+ {
+ var format = new AudioFormat { SampleRate = 48000, Channels = 2, BitsPerSample = 16 };
+ var frames = format.SampleRate;
+ var data = new Byte[frames * format.Channels * 2];
+ for (var i = 0; i < frames; i++)
+ {
+ var v = (Int16)(6000 * Math.Sin(2 * Math.PI * 440 * i / format.SampleRate));
+ for (var c = 0; c < format.Channels; c++)
+ {
+ data[(i * format.Channels + c) * 2] = (Byte)(v & 0xFF);
+ data[(i * format.Channels + c) * 2 + 1] = (Byte)((v >> 8) & 0xFF);
+ }
+ }
+
+ return new AudioPcm { Format = format, Data = data };
}
+ /// <summary>获取驱动:Windows 用 WASAPI(端点 ID 与端点音量),其它平台交给驱动工厂</summary>
+ private IAudioDriver GetDriver() => _driver ??= WasapiDriver.IsPlatformSupported ? new WasapiDriver() : AudioDriverFactory.Create();
+
private void AppendLog(String msg)
{
@@ -96,4 +218,4 @@ public partial class AudioDeviceViewModel : ObservableObject
Log += $"{msg}\r\n";
}
#endregion
-}
+}
\ No newline at end of file
diff --git a/XCoder.App/XCoder.App.csproj b/XCoder.App/XCoder.App.csproj
index 84fa230..a19dd1a 100644
--- a/XCoder.App/XCoder.App.csproj
+++ b/XCoder.App/XCoder.App.csproj
@@ -47,6 +47,7 @@
<PackageReference Include="NewLife.Redis" Version="7.0.2026.1026-beta0931" />
<PackageReference Include="NewLife.Map" Version="2.8.2026.1024" />
<PackageReference Include="NewLife.ModbusRTU" Version="2.1.2026.1024" />
+ <PackageReference Include="NewLife.Audio" Version="1.3.2026.1113-beta1528" />
<PackageReference Include="SSH.NET" Version="2026.0.0" />
<PackageReference Include="System.Data.SQLite.Core" Version="1.0.119" />
<PackageReference Include="System.IO.Ports" Version="11.0.0" />