AudioRecord.h 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. #ifndef AUDIORECORD_H
  2. #define AUDIORECORD_H
  3. #include <cstdint>
  4. #include <list>
  5. #include <string>
  6. #include <alsa/asoundlib.h>
  7. #include <alsa/pcm.h>
  8. /* 声卡的PCM信息结构体 */
  9. struct PCMDevice_t
  10. {
  11. unsigned int PCMDevice; /* PCM设备编号,打开的设备编号就是这个 */
  12. unsigned int SubDevice; /* 子设备编号 */
  13. int CardNumber; /* 声卡编号 */
  14. std::string PCMID; /* 声卡ID */
  15. std::string PCMName; /* 声卡名称 */
  16. std::string PCMSubName; /* 子设备名称 */
  17. };
  18. /**
  19. * @brief 声卡设备信息结构体
  20. *
  21. */
  22. struct AudioDevice_t
  23. {
  24. int CardNumber; /* 声卡编号,打开录音的设备编号是这个 */
  25. std::string CardID; /* 声卡ID */
  26. std::string CardName; /* 声卡名称 */
  27. std::string CardDriver; /* 驱动名称 */
  28. std::string CardLongName; /* 声卡长名称 */
  29. std::string CardMixername; /* 混音器名称 */
  30. std::string CardComponents; /* 组件信息 */
  31. std::list<PCMDevice_t> PCMDevices; /* PCM设备列表 */
  32. };
  33. /**
  34. * @brief 直接获取到的声卡通道描述符信息,可以直接用来打开
  35. *
  36. */
  37. struct AudioDeviceDesc_t
  38. {
  39. std::string DeviceName; /* 设备字符名称,可以直接打开 */
  40. std::string DeviceDesc; /* 设备描述 */
  41. std::string IOID; /* 输入/输出类型 */
  42. std::string Card; /* 声卡编号或标识,可能会没有 */
  43. std::string DevNum; /* 设备编号,可能会没有 */
  44. };
  45. /* 获取声卡信息列表,包括可以用来录音的PCM列表 */
  46. bool getAudioDevices(std::list<AudioDevice_t> &devices);
  47. /* 获取声卡字符设备名称,可以直接被打开 */
  48. bool getPCMAudioDevice(std::list<AudioDeviceDesc_t> &devices);
  49. /**
  50. * @brief 录音类
  51. *
  52. */
  53. class AudioRecord
  54. {
  55. public:
  56. AudioRecord() = default;
  57. ~AudioRecord() = default;
  58. /**
  59. * @brief Set the Record Params object
  60. *
  61. * @param sampleRate 采样率
  62. * @param bits 位深度
  63. * @param channels 通道数
  64. */
  65. void setRecordParams(int sampleRate = 44100, int bits = 16, int channels = 2);
  66. /* 打开录音通道,通常的格式: "hw:0:0" */
  67. bool openRecordChannel(const std::string &deviceName);
  68. /**
  69. * @brief 读取录音大小
  70. *
  71. * @param buffer 数据缓冲区
  72. * @param bufferSize 缓冲区大小
  73. * @param recordFrames 需要读取的帧数,一帧就是一个采样点,16bit / 2 * 2 通道 = 4字节
  74. * 44100帧就是1秒
  75. * @return int 读取到的字节数
  76. */
  77. int recordAudio(char* buffer, uint32_t bufferSize, uint32_t recordFrames);
  78. private:
  79. uint32_t m_sampleRate = 44100; /* 默认采样率 */
  80. int m_bitDepth = 16; /* 默认位深度 */
  81. int m_channels = 2; /* 默认通道数 */
  82. int m_oneSampleSize = 2; /* 单个采样点的大小,默认16位小端格式,2字节 */
  83. std::string m_deviceName; /* 设备名称,打开的设备名称 */
  84. snd_pcm_t* m_captureHandle = nullptr; /* PCM设备句柄 */
  85. };
  86. #endif // AUDIORECORD_H