audio_play_thread.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #pragma once
  2. #include <QAudio>
  3. #include <QAudioDeviceInfo>
  4. #include <QAudioOutput>
  5. #include <QDebug>
  6. #include <QFile>
  7. #include <QIODevice>
  8. #include <QQueue>
  9. #include <QThread>
  10. #include <QWaitCondition>
  11. #include <memory>
  12. #include <atomic>
  13. #include "packets_sync.h"
  14. #define BUFFER_LEN 8192 // 1024
  15. typedef struct AudioData
  16. {
  17. uint16_t len = 0;
  18. char buffer[BUFFER_LEN] = {0};
  19. } AudioData;
  20. typedef struct AudioFrameFmt
  21. {
  22. uint sample_rate;
  23. uint sample_fmt; // AV_SAMPLE_FMT_S16
  24. uint channel;
  25. int byte_order; // QAudioFormat::LittleEndian;
  26. int sample_type; // QAudioFormat::SignedInt
  27. } AudioFrameFmt;
  28. class AudioPlayThread : public QThread
  29. {
  30. Q_OBJECT
  31. public:
  32. explicit AudioPlayThread(QObject* parent = nullptr, VideoState* pState = nullptr);
  33. virtual ~AudioPlayThread();
  34. public:
  35. void print_device() const;
  36. bool init_device(int sample_rate = 8000, int channel = 1, AVSampleFormat sample_fmt = AV_SAMPLE_FMT_S16, float default_vol = 0.8);
  37. void stop_device();
  38. void play_file(const QString& file);
  39. void play_buf(const uint8_t* buf, int datasize);
  40. bool init_resample_param(AVCodecContext* pAudio, AVSampleFormat sample_fmt, VideoState* is);
  41. void final_resample_param();
  42. float get_device_volume() const;
  43. void set_device_volume(float volume);
  44. void send_visual_open(bool bSend = true) { m_bSendToVisual = bSend; };
  45. signals:
  46. void update_play_time();
  47. void data_visual_ready(const AudioData& data);
  48. public slots:
  49. void stop_thread();
  50. protected:
  51. void run() override;
  52. private:
  53. int audio_decode_frame(VideoState* is);
  54. private:
  55. typedef struct Audio_Resample
  56. {
  57. // AVFrame* pFrame;
  58. // uint8_t* buffer;
  59. struct SwrContext* swrCtx{nullptr};
  60. // uint64_t channel_layout; // out
  61. // AVChannelLayout channel_layout;
  62. // AVSampleFormat sample_fmt;
  63. // int sample_rate;
  64. } Audio_Resample;
  65. private:
  66. QAudioOutput* m_pOutput;
  67. QIODevice* m_audioDevice{nullptr};
  68. VideoState* m_pState{nullptr};
  69. Audio_Resample m_audioResample;
  70. std::atomic<bool> m_bExitThread{false}; // 统一为原子变量
  71. bool m_bSendToVisual{false};
  72. };