You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用C#从指定设备录制音频并转换为字节数组?

使用CSCore录制音频并直接获取字节数组

CSCore完全支持直接将录制的音频数据写入内存流,无需先保存到文件,最终可将内存流转换为字节数组。核心思路是用MemoryStream替代文件流来接收音频数据,具体实现分两种场景:获取带WAV头的完整音频数据,或仅获取原始PCM采样数据。

实现步骤与代码示例

1. 安装CSCore

通过NuGet安装库:

Install-Package CSCore

2. 录制完整WAV格式的字节数组

该方法生成的字节数组包含标准WAV文件头和音频数据,可直接写入文件或用于音频播放:

using CSCore;
using CSCore.Codecs.WAV;
using CSCore.SoundIn;
using System.IO;

public class AudioRecorder
{
    public byte[] RecordWavToByteArray(int durationMs, int sampleRate = 44100, int channels = 2, int bitsPerSample = 16)
    {
        // 选择目标录制设备(可替换为指定设备)
        var captureDevice = AudioCaptureDevice.DefaultDevice;
        captureDevice.Format = new WaveFormat(sampleRate, bitsPerSample, channels);

        using var memoryStream = new MemoryStream();
        using var waveWriter = new WaveWriter(memoryStream, captureDevice.Format);

        // 绑定数据接收事件,写入内存流
        captureDevice.DataAvailable += (sender, args) =>
        {
            waveWriter.Write(args.Data, 0, args.ByteCount);
        };

        // 启动录制、等待指定时长后停止
        captureDevice.Start();
        System.Threading.Thread.Sleep(durationMs);
        captureDevice.Stop();

        // 确保数据写入完成
        waveWriter.Flush();

        return memoryStream.ToArray();
    }
}

3. 录制原始PCM字节数组

如果只需要无文件头的原始音频采样数据,可跳过WaveWriter直接写入内存流:

public byte[] RecordRawPcmToByteArray(int durationMs, int sampleRate = 44100, int channels = 2, int bitsPerSample = 16)
{
    var captureDevice = AudioCaptureDevice.DefaultDevice;
    captureDevice.Format = new WaveFormat(sampleRate, bitsPerSample, channels);

    using var memoryStream = new MemoryStream();

    captureDevice.DataAvailable += (sender, args) =>
    {
        memoryStream.Write(args.Data, 0, args.ByteCount);
    };

    captureDevice.Start();
    System.Threading.Thread.Sleep(durationMs);
    captureDevice.Stop();

    return memoryStream.ToArray();
}

4. 指定特定录制设备

若要选择非默认设备,可枚举所有可用设备并筛选:

// 枚举设备并按名称选择
var targetDevice = AudioCaptureDevice.EnumerateDevices()
    .FirstOrDefault(d => d.Name.Contains("你的设备名称"));

if (targetDevice == null)
    throw new System.InvalidOperationException("指定设备未找到");

// 后续使用targetDevice替代AudioCaptureDevice.DefaultDevice

注意事项

  • 需处理设备不存在、格式不支持等异常情况,建议添加try-catch块。
  • Thread.Sleep仅用于简单的固定时长录制,实际项目中可使用异步等待或自定义停止触发逻辑替代。

内容的提问来源于stack exchange,提问作者MrVIPkaMan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 19:27:16