audio_play_thread.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #ifndef AVPLAYER2_AUDIO_PLAY_THREAD_H
  2. #define AVPLAYER2_AUDIO_PLAY_THREAD_H
  3. #pragma once
  4. #include <QAudio>
  5. #include <QAudioDeviceInfo>
  6. #include <QAudioOutput>
  7. #include <QDebug>
  8. #include <QFile>
  9. #include <QIODevice>
  10. #include <QQueue>
  11. #include <QWaitCondition>
  12. #include <memory>
  13. #include <atomic>
  14. #include "packets_sync.h"
  15. #include "ThreadBase.h"
  16. #define BUFFER_LEN 8192 // 1024
  17. typedef struct AudioData
  18. {
  19. uint16_t len = 0;
  20. char buffer[BUFFER_LEN] = {0};
  21. } AudioData;
  22. typedef struct AudioFrameFmt
  23. {
  24. uint sample_rate;
  25. uint sample_fmt; // AV_SAMPLE_FMT_S16
  26. uint channel;
  27. int byte_order; // QAudioFormat::LittleEndian;
  28. int sample_type; // QAudioFormat::SignedInt
  29. } AudioFrameFmt;
  30. class AudioPlayThread : public ThreadBase
  31. {
  32. public:
  33. explicit AudioPlayThread(VideoState* pState = nullptr);
  34. virtual ~AudioPlayThread();
  35. AudioPlayThread(const AudioPlayThread&) = delete;
  36. AudioPlayThread& operator=(const AudioPlayThread&) = delete;
  37. AudioPlayThread(AudioPlayThread&&) = delete;
  38. AudioPlayThread& operator=(AudioPlayThread&&) = delete;
  39. public:
  40. void print_device() const;
  41. bool init_device(int sample_rate = 8000, int channel = 1, AVSampleFormat sample_fmt = AV_SAMPLE_FMT_S16, float default_vol = 0.8);
  42. void stop_device();
  43. void play_file(const QString& file);
  44. void play_buf(const uint8_t* buf, int datasize);
  45. bool init_resample_param(AVCodecContext* pAudio, AVSampleFormat sample_fmt, VideoState* is);
  46. void final_resample_param();
  47. float get_device_volume() const;
  48. void set_device_volume(float volume);
  49. void send_visual_open(bool bSend = true) { m_bSendToVisual = bSend; };
  50. void stop_thread();
  51. void setOnUpdatePlayTime(std::function<void()> cb) { m_onUpdatePlayTime = std::move(cb); }
  52. void setOnDataVisualReady(std::function<void(const AudioData&)> cb) { m_onDataVisualReady = std::move(cb); }
  53. // signals:
  54. // void update_play_time();
  55. // void data_visual_ready(const AudioData& data);
  56. protected:
  57. void run() override;
  58. private:
  59. int audio_decode_frame(VideoState* is);
  60. private:
  61. typedef struct Audio_Resample
  62. {
  63. struct SwrContext* swrCtx{nullptr};
  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. bool m_bSendToVisual{false};
  71. std::function<void()> m_onUpdatePlayTime;
  72. std::function<void(const AudioData&)> m_onDataVisualReady;
  73. };
  74. #endif // AVPLAYER2_AUDIO_PLAY_THREAD_H