AudioPlayer.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #pragma once
  2. extern "C" {
  3. #include <libavutil/channel_layout.h>
  4. #include <libavutil/frame.h>
  5. #include <libavutil/samplefmt.h>
  6. #include <libswresample/swresample.h>
  7. }
  8. struct sonicStreamStruct;
  9. #include <QAudioOutput>
  10. #include <QAudioDeviceInfo>
  11. #include <QIODevice>
  12. #include <QMutex>
  13. class AudioPlayer {
  14. public:
  15. AudioPlayer();
  16. ~AudioPlayer();
  17. // 初始化音频输出,准备播放
  18. bool open(const AVFrame* frame, float speed = 1.0f);
  19. // 播放一帧音频数据
  20. bool play(const AVFrame* frame, float speed = 1.0f);
  21. // 设置播放速度
  22. void setSpeed(float speed);
  23. // 设置音量(0.0~1.0)
  24. void setVolume(float volume);
  25. // 切换音频输出设备
  26. bool setOutputDevice(const QAudioDeviceInfo& deviceInfo);
  27. // 停止播放
  28. void stop();
  29. // 释放所有资源
  30. void reset();
  31. // 获取当前输出设备
  32. QIODevice* getOutputDevice() const;
  33. QAudioOutput* getAudioOutput() const;
  34. float getSpeed() const;
  35. float getVolume() const;
  36. private:
  37. void freeBuffers();
  38. bool initAudioOutput(const AVFrame* frame, float speed);
  39. bool ensureResampler(const AVFrame* frame);
  40. bool ensureSonic(int sampleRate, int channels);
  41. void releaseResampler();
  42. void releaseSonic();
  43. void releaseAudioOutput();
  44. int m_sampleRate = 0;
  45. int m_channels = 0;
  46. AVSampleFormat m_format = AV_SAMPLE_FMT_NONE;
  47. SwrContext* m_swrCtx = nullptr;
  48. uint8_t* m_swrBuffer = nullptr;
  49. int m_swrBufferSize = 0;
  50. sonicStreamStruct* m_sonicCtx = nullptr;
  51. QAudioOutput* m_audioOutput = nullptr;
  52. QIODevice* m_audioDevice = nullptr;
  53. QAudioDeviceInfo m_deviceInfo;
  54. float m_speed = 1.0f;
  55. float m_volume = 1.0f;
  56. uint8_t* m_abufOut = nullptr;
  57. unsigned int m_abufOutSize = 0;
  58. QMutex m_mutex;
  59. };