audio_recorder.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. struct MuxerInfo
  21. {
  22. AvMuxer* muxer;
  23. int streamIndex;
  24. MuxerInfo(AvMuxer* m, int idx) : muxer(m), streamIndex(idx) {}
  25. };
  26. bool Open(const std::vector<AudioCapturer::Type>& deviceTypes,
  27. Encoder<MediaType::AUDIO>::Param& param,
  28. const uint32_t sampleRate = AUDIO_SAMPLE_RATE,
  29. const uint32_t channels = AUDIO_CHANNEL,
  30. const uint32_t bitsPerSample = 32,
  31. const AVSampleFormat format = AUDIO_FMT);
  32. bool LoadMuxer(AvMuxer& muxer);
  33. bool UnloadMuxer(AvMuxer& muxer);
  34. bool StartRecord();
  35. void StopRecord();
  36. void Close();
  37. void PullAndProcessAudio(); // 新增:主动拉取音频数据
  38. auto GetCaptureInfo(int mixIndex) { return _mixer.GetInputInfo(mixIndex); }
  39. void SetVolumeScale(float scale, int mixIndex);
  40. private:
  41. std::vector<IAudioCapturer*> m_audioCapturers;
  42. AudioMixer _mixer;
  43. std::vector<Info> _infos;
  44. std::vector<MuxerInfo> _muxers;
  45. std::mutex _muxersMtx;
  46. bool _isRecord = false;
  47. int _streamIndex;
  48. Encoder<MediaType::AUDIO>::Param _param;
  49. Timer m_audioTimer; // 新增高精度定时器
  50. static constexpr int AUDIO_PULL_INTERVAL_MS = 10;
  51. AVSampleFormat _GetAVSampleFormat(int wBitsPerSample, bool isFloat = true)
  52. {
  53. // isFloat=true 表示32/64位时优先返回浮点格式,否则返回整型
  54. switch (wBitsPerSample) {
  55. case 8:
  56. return AV_SAMPLE_FMT_U8;
  57. case 16:
  58. return AV_SAMPLE_FMT_S16;
  59. case 24:
  60. // FFmpeg没有24bit整型,通常用32bit整型或float
  61. return isFloat ? AV_SAMPLE_FMT_FLT : AV_SAMPLE_FMT_S32;
  62. case 32:
  63. return isFloat ? AV_SAMPLE_FMT_FLT : AV_SAMPLE_FMT_S32;
  64. case 64:
  65. return isFloat ? AV_SAMPLE_FMT_DBL : AV_SAMPLE_FMT_S64;
  66. default:
  67. // 默认返回float
  68. return AV_SAMPLE_FMT_FLT;
  69. }
  70. }
  71. };
  72. #endif