用c++调ffmpeg的接口转mp3为pcm的时候,怎么设定采样率

在调用FFmpeg的接口进行音频解码时,需要设置解码器的参数,包括采样率、声道数等。以下是一个简单的示例:

```c++ // 打开文件 AVFormatContext *formatCtx = nullptr; if (avformatopeninput(&formatCtx, inputFileName.c_str(), nullptr, nullptr) != 0) { // 打开文件失败 return; }

// 获取音频流信息 if (avformatfindstream_info(formatCtx, nullptr) < 0) { // 获取音频流信息失败 avformatcloseinput(&formatCtx); return; }

// 查找音频流 int audioStreamIndex = -1; for (int i = 0; i < formatCtx->nbstreams; i++) { if (formatCtx->streams[i]->codecpar->codectype == AVMEDIATYPEAUDIO) { audioStreamIndex = i; break; } } if (audioStreamIndex == -1) { // 没有找到音频流 avformatcloseinput(&formatCtx); return; }

// 获取解码器 AVCodecParameters *codecParams = formatCtx->streams[audioStreamIndex]->codecpar; AVCodec *codec = avcodecfinddecoder(codecParams->codec_id); if (!codec) { // 没有找到解码器 avformatcloseinput(&formatCtx); return; }

// 创建解码器上下文 AVCodecContext *codecCtx = avcodecalloccontext3(codec); if (!codecCtx) { // 创建解码器上下文失败 avformatcloseinput(&formatCtx); return; }

// 初始化解码器上下文 if (avcodecparameterstocontext(codecCtx, codecParams) < 0) { // 初始化解码器上下文失败 avcodecfreecontext(&codecCtx); avformatclose_input(&formatCtx); return; }

// 打开解码器 if (avcodecopen2(codecCtx, codec, nullptr) != 0) { // 打开解码器失败 avcodecfree_context(&codecCtx); avformatcloseinput(&formatCtx); return; }

// 设置采样率 codecCtx->sample_rate = 44100; // 例如,设置采样率为44100Hz

// 解码音频帧 AVPacket *packet = avpacketalloc(); AVFrame *frame = avframealloc(); while (avreadframe(formatCtx, packet) >= 0) { if (packet->streamindex == audioStreamIndex) { int ret = avcodecsendpacket(codecCtx, packet); if (ret < 0) { // 发送数据到解码器失败 break; } while (ret >= 0) { ret = avcodecreceiveframe(codecCtx, frame); if (ret == AVERROR(EAGAIN) || ret == AVERROREOF) { break; } else if (ret < 0) { // 解码音频帧失败 break; }

        // 处理解码后的音频数据(例如:将MP3格式的音频转换为PCM格式)
        // ...

        av_frame_unref(frame);
    }
}
av_packet_unref(packet);

}

// 释放资源 avframefree(&frame); avpacketfree(&packet); avcodecfreecontext(&codecCtx); avformatcloseinput(&formatCtx); ```

在上述代码中,通过设置codecCtx->sample_rate参数来指定采样率。例如,代码中将采样率设置为44100Hz。注意,采样率应该与音频文件的实际采样率相同,否则可能会出现音质损失或者播放速度变化等问题。

★文末名片可以免费领取音视频开发学习资料,内容包括(FFmpeg ,webRTC ,rtmp ,hls ,rtsp ,ffplay ,srs)以及音视频学习路线图等等。

见下方!↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

猜你喜欢

转载自blog.csdn.net/yinshipin007/article/details/130429103