void AVPlayer::audioCallBack(uint8_t *m_audiobuffer, std::shared_ptr<void> par)
{
// 加锁
m_mutex.lock();
m_audioIndex = m_pDecoder->audioIndex();
int errtimes = 10;
double currenttime = 0.00;
double nexttime = 0.00;
QByteArray audioBuffer;
int desiredBufferSize = 5 * output->periodSize();
// double times = output->bufferSize() / output->periodSize();
while (1)
{
int ret = m_pDecoder->getAFrame(m_audioFrame);
if (ret != 1)
{
if (errtimes == 0)
{
printf("Failed to get audio frame.\n");
break;
}
errtimes--;
printf("Retrying...\n");
continue;
}
// Calculate the next timestamp based on the audio frame's presentation time
double nexttime = m_audioFrame->pts * av_q2d(m_pFormatContext->streams[m_audioIndex]->time_base);
// Convert the frame to PCM
int len = Audio::AudioFFmpeg::GetAudio()->ToPCM(&m_audiobuffer, m_audioFrame, &m_audioBufSize);
// Sleep until the next timestamp
av_usleep(nexttime * 1000000 - currenttime * 1000000);
currenttime = nexttime;
// Accumulate audio data in the buffer
audioBuffer.append(reinterpret_cast<const char *>(m_audiobuffer), len);
// Check if the accumulated data is enough to write
while (audioBuffer.size() >= desiredBufferSize)
{
io->write(audioBuffer.constData(),len);
audioBuffer.remove(0,len); // Remove the written data from the buffer
}
// Update the audio clock
AVPlayer::GetPlay()->m_audioClock.setClock(currenttime);
// Clear the audio buffer
memset(m_audiobuffer, 0, m_audioBufSize);
}
// 释放锁
m_mutex.unlock();
}
把output->bufferSize()缓冲区全部读出就不会有白噪音,但会出现明显卡顿,如果分批读取output->periodSize()则会出现白噪音(蜂鸣声)。