C#教程
主页 > 软件编程 > C#教程 >

C#使用录音并导出录音数据

2024-12-24 | 佚名 | 点击:

一、枚举电脑录音设备,指定设备录音

1、使用Vs2019的Nuget包管理器安装NAudio包

NAudio包

如图所示:

2、创建录音对象并指定录音格式

1

2

3

4

5

6

// 录音对象

WaveInEvent waveIn = new WaveInEvent();

int sampleRate = 48000;   //采样率

int channels = 2;          //录音通道数

int bitsPerSample = 16;     //位深

WaveFormat waveFormat = new WaveFormat(sampleRate, bitsPerSample, channels);

录音格式最好和自己电脑一样,我的电脑格式如下:

3、枚举电脑的可用录音设备,并指定

1

2

3

4

5

6

7

8

9

10

11

12

13

string RecordDeviceName = "麦克风阵列"; //指定麦克风阵列录制

//枚举可用录音设备

for (int i = 0; i < WaveIn.DeviceCount; i++)

{

    var capabilities = WaveIn.GetCapabilities(i);

    Console.WriteLine("DeviceIndex:{0},ProduceName:{1}", i, capabilities.ProductName);

    if (capabilities.ProductName.StartsWith(RecordDeviceName))

    {

        Console.WriteLine("找到指定设备:{0}", RecordDeviceName);

        waveIn.DeviceNumber = i;    //设置该设备为录音设备

    }

}

waveIn.WaveFormat = waveFormat;   //设置录音格式

运行之后枚举的效果如下:

二、获取录音数据

录音数据主要是从waveIn.DataAvailable中获取,我保存了两种形式,一种是将录音直接生成wav文件,另一种是将byte类型的录音数据变换short数据导出到txt中。假如需要对录音数据进行实时处理就直接在DataAvailable这个回调函数中处理即可。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

// 创建WaveFileWriter对象来保存录音数据  路径在bin文件下

WaveFileWriter writer = new WaveFileWriter("recorded.wav", waveFormat);

//编写器

StreamWriter mStreamWriter = new StreamWriter("Record.txt", false, new System.Text.UTF8Encoding(false));

// 设置录音回调函数

int bitIndex = bitsPerSample / 8;

waveIn.DataAvailable += (sender, e) =>

{

    // 将录音数据写入文件

    writer.Write(e.Buffer, 0, e.BytesRecorded);

  

    for (int i = 0; i < e.BytesRecorded/ bitIndex; i++)

    {

        //24bit,导出的数据

        //int sample = (int)((e.Buffer[i * bitIndex + 2] << 16) | (e.Buffer[i * bitIndex + 1] << 8) | e.Buffer[i * bitIndex]);

        //16bit  将两个byte数据组合成一个short数据

        short sample = (short)((e.Buffer[i * bitIndex + 1] << 8) | e.Buffer[i * bitIndex]);

        mStreamWriter.Write("{0},", sample);

    }              

};

try

{

    //尝试打开录音设备,如果设备支持设置的WaveFormat,则能够成功打开

    waveIn.StartRecording();             

    Console.WriteLine("开始录音");

}

catch (Exception ex)

{

    Console.WriteLine($"错误信息:{ex.Message}");

}

Console.WriteLine("请按任意键结束录音");

Console.ReadKey();

waveIn.StopRecording();  //停止录音

writer.Close();

mStreamWriter.Close();

waveIn.Dispose();

三、验证录音数据

可以将txt数据导入到matlab中生成wav文件,然后使用电脑播放器播放wav文件,听一下是否录制到声音。

matlab代码如下:

1

2

3

4

5

6

7

clear,clc,close all;   %清除工作区变量

data=load("Record.txt");  %加载录音数据

left=data(1:2:end);    %左声道数据

right=data(2:2:end);   %右声道数据

doubleChannel=[left',right']; %组合成双声道

doubleChannel=[left',right']./max(abs(doubleChannel));  %录音数据归一化

audiowrite("test.wav",doubleChannel,48000);  %以48000采样率生成wav文件

四、完整代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using NAudio.Wave;

namespace record24位

{

    class Program

    {

        static void Main(string[] args)

        {

            // 录音对象

            WaveInEvent waveIn = new WaveInEvent();

            int sampleRate = 48000;   //采样率

            int channels = 2;          //录音通道数

            int bitsPerSample = 16;     //位深

            WaveFormat waveFormat = new WaveFormat(sampleRate, bitsPerSample, channels);          

            string RecordDeviceName = "麦克风阵列";

            //枚举可用录音设备

            for (int i = 0; i < WaveIn.DeviceCount; i++)

            {

                var capabilities = WaveIn.GetCapabilities(i);

                Console.WriteLine("DeviceIndex:{0},ProduceName:{1}", i, capabilities.ProductName);

                if (capabilities.ProductName.StartsWith(RecordDeviceName))

                {

                    Console.WriteLine("找到指定设备:{0}", RecordDeviceName);

                    waveIn.DeviceNumber = i;    //设置该设备为录音设备

                }

            }

            waveIn.WaveFormat = waveFormat;   //设置录音格式

             

            // 创建WaveFileWriter对象来保存录音数据  路径在bin文件下

            WaveFileWriter writer = new WaveFileWriter("recorded.wav", waveFormat);

            //编写器

            StreamWriter mStreamWriter = new StreamWriter("Record.txt", false, new System.Text.UTF8Encoding(false));

            // 设置录音回调函数

            int bitIndex = bitsPerSample / 8;

            waveIn.DataAvailable += (sender, e) =>

            {

                // 将录音数据写入文件

                writer.Write(e.Buffer, 0, e.BytesRecorded);

  

                for (int i = 0; i < e.BytesRecorded/ bitIndex; i++)

                {

                    //24bit,导出的数据

                    //int sample = (int)((e.Buffer[i * bitIndex + 2] << 16) | (e.Buffer[i * bitIndex + 1] << 8) | e.Buffer[i * bitIndex]);

                    //16bit  将两个byte数据组合成一个short数据

                    short sample = (short)((e.Buffer[i * bitIndex + 1] << 8) | e.Buffer[i * bitIndex]);

                    mStreamWriter.Write("{0},", sample);

                }              

            };

            try

            {

                //尝试打开录音设备,如果设备支持设置的WaveFormat,则能够成功打开

                waveIn.StartRecording();             

                Console.WriteLine("开始录音");

            }

            catch (Exception ex)

            {

                Console.WriteLine($"错误信息:{ex.Message}");

            }

            Console.WriteLine("请按任意键结束录音");

            Console.ReadKey();

            waveIn.StopRecording();  //停止录音

            writer.Close();

            mStreamWriter.Close();

            waveIn.Dispose();

  

        }

    }

}

原文链接:
相关文章
最新更新