audio_recorder.h 2.5 KB

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