-
Notifications
You must be signed in to change notification settings - Fork 0
/
audiothreadutil.cpp
150 lines (142 loc) · 3.28 KB
/
audiothreadutil.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#include "audiothreadutil.h"
AudioThreadUtil::AudioThreadUtil()
{
if (!resampleUtil)
{
resampleUtil = new ResampleUtil();
}
if (!audioPlay)
{
audioPlay = AudioPlay::Get();
}
}
AudioThreadUtil::~AudioThreadUtil()
{
isExit = true;
wait();
}
// 音频播放
void AudioThreadUtil::run()
{
unsigned char* pcm = new unsigned char[1024 * 1024 * 10];
while (!isExit)
{
audioLock.lock();
if (isPause)
{
audioLock.unlock();
msleep(5);
continue;
}
AVPacket* pkt = PopPacket();
bool result = decodeUtil->Send(pkt);
if (!result)
{
audioLock.unlock();
msleep(1);
continue;
}
// 有可能一次Send多次Receive
while (!isExit)
{
AVFrame* frame = decodeUtil->Receive();
if (!frame)
{
break;
}
// 减去缓冲中未播放的时间
standard_pts = decodeUtil->standard_pts - audioPlay->GetPtsDifference();
// 重采样
int resample_size = resampleUtil->Resample(frame, pcm);
// 播放音频
while (!isExit)
{
if (resample_size <= 0)
{
break;
}
// 缓冲未播完,空间不够
if (audioPlay->GetFree() < resample_size || isPause)
{
msleep(1);
continue;
}
audioPlay->Write(pcm, resample_size);
break;
}
}
audioLock.unlock();
}
delete [] pcm;
}
// 初始化
bool AudioThreadUtil::Open(AVCodecParameters* codec_param)
{
if(!codec_param)
{
return false;
}
Clear();
audioLock.lock();
standard_pts = 0;
bool result = true;
if (!resampleUtil->Open(codec_param, false))
{
qDebug() << QString::fromLocal8Bit("重采样打开失败");
result = false;
}
if (!audioPlay->Open(codec_param->sample_rate, 16, codec_param->channels))
{
qDebug() << QString::fromLocal8Bit("音频播放打开失败");
result = false;
}
if (!decodeUtil->Open(codec_param))
{
qDebug() << QString::fromLocal8Bit("解码打开失败");
result = false;
}
audioLock.unlock();
return result;
}
// 清理
void AudioThreadUtil::Clear()
{
DecodeThreadUtil::Clear();
// 此处加速 暂停时无法快进
// audioLock.lock();
if (audioPlay)
{
audioPlay->Clear();
}
// audioLock.unlock();
}
// 关闭
void AudioThreadUtil::Close()
{
DecodeThreadUtil::Close();
if (resampleUtil)
{
resampleUtil->Close();
audioLock.lock();
delete resampleUtil;
resampleUtil = nullptr;
audioLock.unlock();
}
if (audioPlay)
{
audioLock.lock();
audioPlay->Close();
audioPlay = nullptr;
audioLock.unlock();
}
}
// 设置暂停
void AudioThreadUtil::SetPause(bool isPause)
{
qDebug() << QString::fromLocal8Bit("AudioThreadUtil::SetPause") << isPause;
this->isPause = isPause;
if (audioPlay)
{
audioPlay->SetPause(isPause);
}
}