audio_recorder.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #ifndef __AUDIO_RECORDER_H__
  2. #define __AUDIO_RECORDER_H__
  3. #include "capturer/audio/audio_capturer.h"
  4. #include "encoder/audio_mixer.h"
  5. #include "muxer/av_muxer.h"
  6. #include "basic/timer.h"
  7. class AudioRecorder
  8. {
  9. public:
  10. AudioRecorder();
  11. ~AudioRecorder();
  12. struct Info
  13. {
  14. AudioMixer* mixer = nullptr;
  15. AvMuxer* muxer = nullptr;
  16. bool* isRecord = nullptr;
  17. int mixIndex;
  18. int* streamIndex = nullptr;
  19. };
  20. bool Open(const std::vector<AudioCapturer::Type>& deviceTypes,
  21. Encoder<MediaType::AUDIO>::Param& param,
  22. const uint32_t sampleRate = AUDIO_SAMPLE_RATE,
  23. const uint32_t channels = AUDIO_CHANNEL,
  24. const uint32_t bitsPerSample = 32,
  25. const AVSampleFormat format = AUDIO_FMT);
  26. bool LoadMuxer(AvMuxer& muxer);
  27. bool StartRecord();
  28. void StopRecord();
  29. void Close();
  30. void PullAndProcessAudio(); // 新增:主动拉取音频数据
  31. auto GetCaptureInfo(int mixIndex) { return _mixer.GetInputInfo(mixIndex); }
  32. void SetVolumeScale(float scale, int mixIndex);
  33. private:
  34. std::vector<IAudioCapturer*> m_audioCapturers;
  35. AudioMixer _mixer;
  36. std::vector<Info> _infos;
  37. bool _isRecord = false;
  38. int _streamIndex;
  39. Encoder<MediaType::AUDIO>::Param _param;
  40. Timer m_audioTimer; // 新增高精度定时器
  41. static constexpr int AUDIO_PULL_INTERVAL_MS = 10;
  42. AVSampleFormat _GetAVSampleFormat(int wBitsPerSample, bool isFloat = true)
  43. {
  44. // isFloat=true 表示32/64位时优先返回浮点格式,否则返回整型
  45. switch (wBitsPerSample) {
  46. case 8:
  47. return AV_SAMPLE_FMT_U8;
  48. case 16:
  49. return AV_SAMPLE_FMT_S16;
  50. case 24:
  51. // FFmpeg没有24bit整型,通常用32bit整型或float
  52. return isFloat ? AV_SAMPLE_FMT_FLT : AV_SAMPLE_FMT_S32;
  53. case 32:
  54. return isFloat ? AV_SAMPLE_FMT_FLT : AV_SAMPLE_FMT_S32;
  55. case 64:
  56. return isFloat ? AV_SAMPLE_FMT_DBL : AV_SAMPLE_FMT_S64;
  57. default:
  58. // 默认返回float
  59. return AV_SAMPLE_FMT_FLT;
  60. }
  61. }
  62. };
  63. #endif