audio_output.h 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. #ifndef AV_PLAYER_AUDIO_OUTPUT_H
  2. #define AV_PLAYER_AUDIO_OUTPUT_H
  3. #include <QAudioOutput>
  4. #include <QAudioFormat>
  5. #include <QIODevice>
  6. #include <QMutex>
  7. #include <QWaitCondition>
  8. #include <QThread>
  9. #include <memory>
  10. #include <atomic>
  11. #include <queue>
  12. extern "C" {
  13. #include <libavutil/frame.h>
  14. #include <libavutil/samplefmt.h>
  15. #include <libswresample/swresample.h>
  16. }
  17. #include "../base/media_common.h"
  18. namespace av {
  19. namespace player {
  20. /**
  21. * 音频输出设备类
  22. * 负责将解码后的音频帧输出到扬声器
  23. */
  24. class AudioOutput : public QObject
  25. {
  26. Q_OBJECT
  27. public:
  28. explicit AudioOutput(QObject* parent = nullptr);
  29. ~AudioOutput();
  30. /**
  31. * 初始化音频输出设备
  32. * @param sampleRate 采样率
  33. * @param channels 声道数
  34. * @param sampleFormat 采样格式
  35. * @return 是否成功
  36. */
  37. bool initialize(int sampleRate, int channels, AVSampleFormat sampleFormat);
  38. /**
  39. * 开始播放
  40. */
  41. void start();
  42. /**
  43. * 停止播放
  44. */
  45. void stop();
  46. /**
  47. * 暂停播放
  48. */
  49. void pause();
  50. /**
  51. * 恢复播放
  52. */
  53. void resume();
  54. /**
  55. * 写入音频帧
  56. * @param frame 音频帧
  57. * @return 是否成功
  58. */
  59. bool writeFrame(const AVFramePtr& frame);
  60. /**
  61. * 设置音量
  62. * @param volume 音量 (0.0 - 1.0)
  63. */
  64. void setVolume(double volume);
  65. /**
  66. * 获取音量
  67. */
  68. double getVolume() const;
  69. /**
  70. * 清空缓冲区
  71. */
  72. void flush();
  73. /**
  74. * 获取缓冲区大小(毫秒)
  75. */
  76. int getBufferSize() const;
  77. /**
  78. * 是否正在播放
  79. */
  80. bool isPlaying() const;
  81. private slots:
  82. void onStateChanged(QAudio::State state);
  83. private:
  84. /**
  85. * 初始化重采样器
  86. */
  87. bool initResampler();
  88. /**
  89. * 清理重采样器
  90. */
  91. void cleanupResampler();
  92. /**
  93. * 转换音频帧格式
  94. */
  95. QByteArray convertFrame(const AVFramePtr& frame);
  96. /**
  97. * 应用音量控制
  98. */
  99. void applyVolume(QByteArray& data);
  100. private:
  101. QAudioOutput* m_audioOutput;
  102. QIODevice* m_audioDevice;
  103. QAudioFormat m_audioFormat;
  104. // 音频参数
  105. int m_sampleRate;
  106. int m_channels;
  107. AVSampleFormat m_inputFormat;
  108. // 重采样器
  109. SwrContext* m_swrContext;
  110. bool m_needResampling;
  111. // 音量控制
  112. std::atomic<double> m_volume;
  113. // 状态
  114. std::atomic<bool> m_initialized;
  115. std::atomic<bool> m_playing;
  116. mutable QMutex m_mutex;
  117. };
  118. } // namespace player
  119. } // namespace av
  120. #endif // AV_PLAYER_AUDIO_OUTPUT_H