audio_play_thread.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. public:
  36. void print_device() const;
  37. bool init_device(int sample_rate = 8000, int channel = 1, AVSampleFormat sample_fmt = AV_SAMPLE_FMT_S16, float default_vol = 0.8);
  38. void stop_device();
  39. void play_file(const QString& file);
  40. void play_buf(const uint8_t* buf, int datasize);
  41. bool init_resample_param(AVCodecContext* pAudio, AVSampleFormat sample_fmt, VideoState* is);
  42. void final_resample_param();
  43. float get_device_volume() const;
  44. void set_device_volume(float volume);
  45. void send_visual_open(bool bSend = true) { m_bSendToVisual = bSend; };
  46. void setOnUpdatePlayTime(std::function<void()> cb) { m_onUpdatePlayTime = std::move(cb); }
  47. void setOnDataVisualReady(std::function<void(const AudioData&)> cb) { m_onDataVisualReady = std::move(cb); }
  48. protected:
  49. void run() override;
  50. private:
  51. int audio_decode_frame(VideoState* is);
  52. private:
  53. typedef struct Audio_Resample
  54. {
  55. struct SwrContext* swrCtx{nullptr};
  56. } Audio_Resample;
  57. private:
  58. QAudioOutput* m_pOutput;
  59. QIODevice* m_audioDevice{nullptr};
  60. VideoState* m_pState{nullptr};
  61. Audio_Resample m_audioResample;
  62. bool m_bSendToVisual{false};
  63. std::function<void()> m_onUpdatePlayTime;
  64. std::function<void(const AudioData&)> m_onDataVisualReady;
  65. };
  66. #endif // AVPLAYER2_AUDIO_PLAY_THREAD_H