sonic库源码:https://github.com/waywardgeek/sonic
//创建对象
sonicStream sncStream=sonicCreateStream(audio->audioContext->sample_rate, audio->audioContext->channels);
//设置倍速
sonicSetSpeed(sncStream, speed);
sonicSetPitch(sncStream, 1.0);
sonicSetRate(sncStream, 1.0);
//写入音频裸流
int ret = sonicWriteShortToStream(sncStream, (short*)audio->getAudioBuff(), audio_size/(audio->audioContext->channels * av_get_bytes_per_sample(AV_SAMPLE_FMT_S16)));
//int ret = sonicWriteShortToStream(sncStream, (float*)audio->getAudioBuff(), audio_size/(audio->audioContext->channels * av_get_bytes_per_sample(AV_SAMPLE_FMT_S16)));
int new_buffer_size;
int num_samples = sonicSamplesAvailable(sncStream);
//计算缓冲区大小
int size = num_samples * audio->audioContext->channels * av_get_bytes_per_sample(AV_SAMPLE_FMT_S16);
if (audio_size < size)
{
speed_buf = new uint8_t[size];
speed_buf_size = size;
}
if (ret)
{
// 从流中读取处理好的数据
new_buffer_size = sonicReadShortFromStream(sncStream, (short*)speed_buf, num_samples);
//new_buffer_size = sonicReadFloatFromStream(sncStream, (float*)audio->getAudioBuff(), numSamples);
}
audio->audioBuff = (uint8_t*)speed_buf;
audio_size = new_buffer_size * audio->audioContext->channels * av_get_bytes_per_sample(AV_SAMPLE_FMT_S16);
audio->setAudioBuffSize(audio_size);
//销毁对象
sonicDestroyStream(sncStream);
audio->setAudioBuffSize(audio_size);
其中audio->getAudioBuff() 以及audio->audioBuff就是音频解码后的PCM数据
int size = num_samples * audio->audioContext->channels * av_get_bytes_per_sample(AV_SAMPLE_FMT_S16);
由于sonic库处理的数据为short类型或者float类型,但是ffmpeg重采样后的数据和SDL使用的数据都是uint8类型,所以这里数据长度就需要重新计算:原始的数据长度/(音频通道数 * S16类型数据所占字节数)