FFmpeg - 打造一款萬能的音樂播放器

從 c/c++ 基礎(chǔ)、jni 基礎(chǔ)、c/c++ 進(jìn)階、數(shù)據(jù)結(jié)構(gòu)和算法、linux 內(nèi)核、CMake 語法、Shell 腳本繞了一大圈之后,總算是勉強(qiáng)可以來寫 FFmpeg 了,以上這些基礎(chǔ)大家可以看下之前的文章:

效果演示

今天帶大家來實(shí)現(xiàn)一個(gè)比較常見的功能,像 QQ音樂、酷狗音樂、網(wǎng)易云音樂這樣的一些應(yīng)用,都涉及到音樂的播放。首先我們來介紹一下需要用到的一些函數(shù),剛開始大家只需要知道他們怎么用,用來干什么的基本就足夠了,漸漸到后面再去了解源碼,再去深入手寫算法。先來看一張流程圖:

解碼流程
  • av_register_all():的作用是初始化所有組件,只有調(diào)用了該函數(shù),才能使用復(fù)用器和編解碼器(源碼)
  • avformat_open_input()/avformat_close_input(): 函數(shù)會(huì)讀文件頭,對 mp4 文件而言,它會(huì)解析所有的 box。但它知識把讀到的結(jié)果保存在對應(yīng)的數(shù)據(jù)結(jié)構(gòu)下。這個(gè)時(shí)候,AVStream 中的很多字段都是空白的。
  • av_dump_format(): 打印視音頻信息
  • avformat_find_stream_info():讀取一部分視音頻數(shù)據(jù)并且獲得一些相關(guān)的信息,會(huì)檢測一些重要字段,如果是空白的,就設(shè)法填充它們。因?yàn)槲覀兘馕鑫募^的時(shí)候,已經(jīng)掌握了大量的信息,avformat_find_stream_info 就是通過這些信息來填充自己的成員,當(dāng)重要的成員都填充完畢后,該函數(shù)就返回了。這中情況下,該函數(shù)效率很高。但對于某些文件,單純的從文件頭中獲取信息是不夠的,比如 video 的 pix_fmt 是需要調(diào)用 h264_decode_frame 才可以獲取其pix_fmt的。
  • av_find_best_stream(): 獲取音視頻及字幕的 stream_index , 以前沒有這個(gè)函數(shù)時(shí),我們一般都是寫的 for 循環(huán)。
  • av_packet_free(): 首先將 AVPacket 指向的數(shù)據(jù)域的引用技術(shù)減1(數(shù)據(jù)域的引用技術(shù)減為0時(shí)會(huì)自動(dòng)釋放) 接著,釋放為 AVPacket 分配的空間。
  • av_packet_unref(): 減少數(shù)據(jù)域的引用技術(shù),當(dāng)引用技術(shù)減為0時(shí),會(huì)自動(dòng)釋放數(shù)據(jù)域所占用的空間。

1. 獲取音頻 Meta 信息

就在前幾天有同學(xué)問了我一個(gè)問題,對于 amr 格式的音頻文件而言,我如何去獲取它的采樣率以及是否是單通道。如果用 ffmpeg 那很 easy 就能解決,但問題是不會(huì),那么我們就只能用其他的第三方庫。當(dāng)然如果你了解其原理,甚至可以自己分析二進(jìn)制文件。

extern "C"
JNIEXPORT void JNICALL
Java_com_darren_ndk_day03_NativeMedia_printAudioInfo(JNIEnv *env, jclass j_cls, jstring url_) {
    const char *url = env->GetStringUTFChars(url_, 0);

    av_register_all();

    AVFormatContext *avFormatContext = NULL;
    int audio_stream_idx;
    AVStream *audio_stream;

    int open_res = avformat_open_input(&avFormatContext, absolutePath, NULL, NULL);
    if (open_res != 0) {
        LOGE("Can't open file: %s", av_err2str(open_res));
        return;
    }
    int find_stream_info_res = avformat_find_stream_info(avFormatContext, NULL);
    if (find_stream_info_res < 0) {
        LOGE("Find stream info error: %s", av_err2str(find_stream_info_res));
        goto __avformat_close;
    }

    // 獲取采樣率和通道
    audio_stream_idx = av_find_best_stream(avFormatContext, AVMediaType::AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0);
    if (audio_stream_idx < 0) {
        LOGE("Find audio stream info error: %s", av_err2str(find_stream_info_res));
        goto __avformat_close;
    }
    audio_stream = avFormatContext->streams[audio_stream_idx];
    LOGE("采樣率:%d, 通道數(shù): %d", audio_stream->codecpar->sample_rate, audio_stream->codecpar->channels);

    __avformat_close:
    avformat_close_input(&avFormatContext);
    env->ReleaseStringUTFChars(url_, url);
}

2. 解碼音頻數(shù)據(jù)

關(guān)于解碼函數(shù) avcodec_decode_audio4 已經(jīng)過時(shí)了,取而代之的是 avcodec_send_packet 和 avcodec_receive_frame 。

    // 這個(gè)方法過時(shí)了
    // pCodecContext = av_format_context->streams[video_stream_idx]->codec;
    pCodecParameters = av_format_context->streams[audio_stream_idx]->codecpar;
    // 查找解碼器
    pCodec = avcodec_find_decoder(pCodecParameters->codec_id);
    if (!pCodec) {
        LOGE("Can't find audio decoder : %s", url);
        goto __avresource_close;
    }

    // 初始化創(chuàng)建 AVCodecContext
    pCodecContext = avcodec_alloc_context3(pCodec);
    codecContextParametersRes = avcodec_parameters_to_context(pCodecContext, pCodecParameters);
    if (codecContextParametersRes < 0) {
        LOGE("codec parameters to_context error : %s, %s", url,av_err2str(codecContextParametersRes));
        goto __avresource_close;
    }

    // 打開解碼器
    codecOpenRes = avcodec_open2(pCodecContext, pCodec, NULL);
    if (codecOpenRes < 0) {
        LOGE("codec open error : %s, %s", url, av_err2str(codecOpenRes));
        goto __avresource_close;
    }

    // 提取每一幀的音頻流
    avPacket = av_packet_alloc();
    avFrame = av_frame_alloc();
    while (av_read_frame(av_format_context, avPacket) >= 0) {
        if (audio_stream_idx == avPacket->stream_index) {
            // 可以寫入文件、截取、重采樣、解碼等等 avPacket.data
            sendPacketRes = avcodec_send_packet(pCodecContext, avPacket);
            if (sendPacketRes == 0) {
                receiveFrameRes = avcodec_receive_frame(pCodecContext, avFrame);
                if (receiveFrameRes == 0) {
                    LOGE("解碼第 %d 幀", index);
                }
            }
            index++;
        }
        // av packet unref
        av_packet_unref(avPacket);
        av_frame_unref(avFrame);
    }

    // 釋放資源 ============== start
    av_packet_free(&avPacket);
    av_frame_free(&avFrame);

    __avresource_close:

    if(pCodecContext != NULL){
        avcodec_close(pCodecContext);
        avcodec_free_context(&pCodecContext);
    }
    
    if (av_format_context != NULL) {
        avformat_close_input(&av_format_context);
        avformat_free_context(av_format_context);
    }
    
    env->ReleaseStringUTFChars(url_, url);
    // 釋放資源 ============== end

3. 播放音頻

播放 pcm 數(shù)據(jù)目前比較流行的有兩種方式,一種是通過 Android 的 AudioTrack 來播放,另一種是采用跨平臺的 OpenSLES 來播放,個(gè)人比較傾向于用更加高效的 OpenSLES 來播放音頻,大家可以先看看 Google 官方的 native-audio 事例,后面我們寫音樂播放器時(shí),會(huì)采用 OpenSLES 來播放音頻。但這里我們還是采用 AudioTrack 來播放


jobject initCreateAudioTrack(JNIEnv *env) {
    jclass jAudioTrackClass = env->FindClass("android/media/AudioTrack");
    jmethodID jAudioTrackCMid = env->GetMethodID(jAudioTrackClass, "<init>", "(IIIIII)V");

    //  public static final int STREAM_MUSIC = 3;
    int streamType = 3;
    int sampleRateInHz = 44100;
    // public static final int CHANNEL_OUT_STEREO = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT);
    int channelConfig = (0x4 | 0x8);
    // public static final int ENCODING_PCM_16BIT = 2;
    int audioFormat = 2;
    // getMinBufferSize(int sampleRateInHz, int channelConfig, int audioFormat)
    jmethodID jGetMinBufferSizeMid = env->GetStaticMethodID(jAudioTrackClass, "getMinBufferSize", "(III)I");
    int bufferSizeInBytes = env->CallStaticIntMethod(jAudioTrackClass, jGetMinBufferSizeMid, sampleRateInHz, channelConfig, audioFormat);
    // public static final int MODE_STREAM = 1;
    int mode = 1;
    jobject jAudioTrack = env->NewObject(jAudioTrackClass, jAudioTrackCMid, streamType, sampleRateInHz, channelConfig, audioFormat, bufferSizeInBytes, mode);

    // play()
    jmethodID jPlayMid = env->GetMethodID(jAudioTrackClass, "play", "()V");
    env->CallVoidMethod(jAudioTrack, jPlayMid);

    return jAudioTrack;
}

{
    // 初始化重采樣 ====================== start
    swrContext = swr_alloc();
    //輸入的采樣格式
    inSampleFmt = pCodecContext->sample_fmt;
    //輸出采樣格式16bit PCM
    outSampleFmt = AV_SAMPLE_FMT_S16;
    //輸入采樣率
    inSampleRate = pCodecContext->sample_rate;
    //輸出采樣率
    outSampleRate = AUDIO_SAMPLE_RATE;
    //獲取輸入的聲道布局
    //根據(jù)聲道個(gè)數(shù)獲取默認(rèn)的聲道布局(2個(gè)聲道,默認(rèn)立體聲stereo)
    inChLayout = pCodecContext->channel_layout;
    //輸出的聲道布局(立體聲)
    outChLayout = AV_CH_LAYOUT_STEREO;

    swr_alloc_set_opts(swrContext, outChLayout, outSampleFmt, outSampleRate, inChLayout,
            inSampleFmt, inSampleRate,0, NULL);

    resampleOutBuffer = (uint8_t *) av_malloc(AUDIO_SAMPLES_SIZE_PER_CHANNEL);
    outChannelNb = av_get_channel_layout_nb_channels(outChLayout);
    dataSize = av_samples_get_buffer_size(NULL, outChannelNb,pCodecContext->frame_size,
            outSampleFmt, 1);

    if (swr_init(swrContext) < 0) {
        LOGE("Failed to initialize the resampling context");
        return;
    }
    // 初始化重采樣 ====================== end

    // 提取每一幀的音頻流
    avPacket = av_packet_alloc();
    avFrame = av_frame_alloc();
    while (av_read_frame(av_format_context, avPacket) >= 0) {
        if (audio_stream_idx == avPacket->stream_index) {
            // 可以寫入文件、截取、重采樣、解碼等等 avPacket.data
            sendPacketRes = avcodec_send_packet(pCodecContext, avPacket);
            if (sendPacketRes == 0) {
                receiveFrameRes = avcodec_receive_frame(pCodecContext, avFrame);

                if(receiveFrameRes == 0){
                    // 往 AudioTrack 對象里面塞數(shù)據(jù)  avFrame->data -> jbyte;
                    swr_convert(swrContext, &resampleOutBuffer, avFrame->nb_samples,
                            (const uint8_t **) avFrame->data, avFrame->nb_samples);

                    jbyteArray jPcmDataArray = env->NewByteArray(dataSize);
                    jbyte *jPcmData = env->GetByteArrayElements(jPcmDataArray, NULL);
                    memcpy(jPcmData, resampleOutBuffer, dataSize);
                    // 同步刷新到 jbyteArray ,并釋放 C/C++ 數(shù)組
                    env->ReleaseByteArrayElements(jPcmDataArray, jPcmData, 0);

                    // call java write
                    env->CallIntMethod(audioTrack, jWriteMid, jPcmDataArray, 0, dataSize);

                    // 解除 jPcmDataArray 的持有,讓 javaGC 回收
                    env->DeleteLocalRef(jPcmDataArray);
                }
            }
            index++;
        }
        // av packet unref
        av_packet_unref(avPacket);
        av_frame_unref(avFrame);
    }

}
  • 剛開始看源碼時(shí),我們一般無法徹底的搞懂函數(shù)的方方面面,但是,通過源碼分析,能更好的理解了這個(gè)函數(shù)的功能,對這個(gè)函數(shù)做的事情也會(huì)有一定的了解。至于那些搞不懂的,就只能留著以后慢慢研究了。比如 avformat_find_stream_info() 函數(shù)會(huì)計(jì)算 start_time,波特率等信息,其中時(shí)間相關(guān)的計(jì)算很復(fù)雜,如果剛開始沒能看懂,可以以后慢慢再去啃。
  • 我在網(wǎng)上看了一些例子,大家基本都是一套模子的代碼,而且運(yùn)行時(shí)內(nèi)存在蹭蹭的往上漲,當(dāng)然早期我也犯過同樣類似的錯(cuò)誤。因此我想提醒大家是,最好還是要能理解其中的原理,網(wǎng)上直接拿過來的代碼可能會(huì)有些問題,包括我寫的代碼可能也會(huì)有些問題,需要大家多留個(gè)心眼多一些思考。
  • 上面的代碼只是一個(gè)事例,它并不能用到真正的項(xiàng)目中,關(guān)于多線程邊解碼邊播放,關(guān)于怎樣使用 OpenSL ES 播放 PCM 數(shù)據(jù),怎樣添加加載、播放、暫停等狀態(tài)功能,怎樣實(shí)現(xiàn)聲道變化,怎樣變速變調(diào),怎樣 seek 等等。后面我們都會(huì)手把手一起來完善的,且會(huì)將代碼開源到我的個(gè)人 github,供大家參考和學(xué)習(xí)。

視頻地址:https://pan.baidu.com/s/1CbXdB9kzvvSTozeFD2ZRHw
視頻密碼:cse5

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容