android開發(fā)之音頻拼接

第一種情況:不同壓縮格式音頻拼接,不同的壓縮格式拼接需要解碼為采樣數(shù)據(jù)然后拼接,然后再編碼為統(tǒng)一的壓縮格式铡买。


這里寫圖片描述

方法一:FFmpeg命令拼接,ffmpeg -I 'concat:0.mp3|1.wav|2.aac' -acodec copy merge.mp3霎箍。

  static {
        System.loadLibrary("MyLib");
    }
  public native void command(int len,String[] argv);
 /**
     * 使用ffmpeg命令行進(jìn)行音頻合并
     * @param src 源文件
     * @param targetFile 目標(biāo)文件
     * @return 合并后的文件
     */
    public static  String[] concatAudio(String[] src, String targetFile){
        String join = StringUtils.join("|", src);
        String concatAudioCmd = "ffmpeg -i concat:%s -acodec copy %s";//%s|%s
        concatAudioCmd = String.format(concatAudioCmd, join, targetFile);
        return concatAudioCmd.split(" ");//以空格分割為字符串?dāng)?shù)組
    }
    
   /**
     * 拼接音頻
     * @param paths 音頻地址集合
     * @return 音頻拼接之后的地址
     */
    private String jointAudio1(List<String> paths) {
        String path = "";
        for (int i = 1; i < paths.size(); i++) {
            String[] pathArr = new String[2];
                if (i==1) {
                    pathArr[0] = paths.get(i - 1);
                    pathArr[1] = paths.get(i);
                }else{
                    pathArr[0] = path;
                    pathArr[1] = paths.get(i);
                }
            File file = new File(paths.get(0));
            path = file.getParent().concat(File.separator).concat(String.valueOf(System.currentTimeMillis()).concat("-debris.mp3"));
            String[] command = FFmpegUtil.concatAudio(pathArr, path);
            command(command.length,command);
        }
        return path;
    }
#include <jni.h>
#include <malloc.h>
#include <string.h>
#include "ffmpeg.h"
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include <libavutil/imgutils.h>
#include <libswscale/swscale.h>
//音頻采樣
#include <libswresample/swresample.h>
#include <android/log.h>
#define LOG_I_ARGS(FORMAT,...) __android_log_print(ANDROID_LOG_INFO,"main",FORMAT,__VA_ARGS__);
#define LOG_I(FORMAT) LOG_I_ARGS(FORMAT,0);

//視頻轉(zhuǎn)碼壓縮主函數(shù)入口
//ffmpeg_mod.c有一個(gè)FFmpeg視頻轉(zhuǎn)碼主函數(shù)入口
// argc = str.split(" ").length()
// argv = str.split(" ")  字符串?dāng)?shù)組
//參數(shù)一:命令行字符串命令個(gè)數(shù)
//參數(shù)二:命令行字符串?dāng)?shù)組
int ffmpegmain(int argc, char **argv);


JNIEXPORT void JNICALL Java_com_xy_openndk_audiojointdemo_FFmpegLib_command
        (JNIEnv *env, jobject jobj,jint jlen,jobjectArray jobjArray){
    //轉(zhuǎn)碼
    //將java的字符串?dāng)?shù)組轉(zhuǎn)成C字符串
    int argc = jlen;
    //開辟內(nèi)存空間
    char **argv = (char**)malloc(sizeof(char*) * argc);

    //填充內(nèi)容
    for (int i = 0; i < argc; ++i) {
        jstring str = (*env)->GetObjectArrayElement(env,jobjArray,i);
        const char* tem = (*env)->GetStringUTFChars(env,str,0);
        argv[i] = (char*)malloc(sizeof(char)*1024);
        strcpy(argv[i],tem);
        (*env)->ReleaseStringUTFChars(env,str,tem);
    }
    //開始轉(zhuǎn)碼(底層實(shí)現(xiàn)就是只需命令)
    ffmpegmain(argc,argv);
    //釋放內(nèi)存空間
    for (int i = 0; i < argc; ++i) {
        free(argv[I]);
    }
    //釋放數(shù)組
    free(argv);
}

方法二:FFmpeg解碼為采樣數(shù)據(jù)之后拼接采樣數(shù)據(jù)奇钞,然后再編碼為壓縮格式數(shù)據(jù)。(這里我選用了FFmpeg進(jìn)行編解碼漂坏,當(dāng)然也可以選擇Android系統(tǒng)提供的MediaCodec進(jìn)行解碼拼接再編碼)

include <jni.h>
#include <android/log.h>
extern "C" {
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavutil/imgutils.h"
#include "libswscale/swscale.h"
//音頻采樣
#include "libswresample/swresample.h"
#include "mp3enc/lame.h"
}
#define LOG_I_ARGS(FORMAT, ...) __android_log_print(ANDROID_LOG_INFO,"main",FORMAT,__VA_ARGS__);
#define LOG_I(FORMAT) LOG_I_ARGS(FORMAT,0);
#define MAX_AUDIO_FRAME_SIZE (44100)
AVFormatContext *av_fm_ctx = NULL;
AVCodecParameters *av_codec_pm = NULL;
AVCodec *av_codec = NULL;
AVCodecContext *av_codec_ctx = NULL;
AVPacket *packet = NULL;
AVFrame *in_frame = NULL;
SwrContext *swr_ctx = NULL;
uint8_t *out_buffer = NULL;

/**
 * 音頻解碼
 * @param out 拼接的采樣數(shù)據(jù)文件
 * @param path 音頻地址
 */
void decodeAudio(FILE *out, const char *path);

/**
 * 音頻編碼
 * @param path PCM文件地址
 * @param out 輸出文件地址
 */
void encoder(const char* path,const char* out);

extern "C"
JNIEXPORT void JNICALL
Java_com_xy_audio_ffmpegjointaudio_MainActivity_jointAudio(JNIEnv *env, jobject instance,
                                                           jobjectArray paths_, jstring path_,jstring other_) {
    jsize len = env->GetArrayLength(paths_);
    //音頻輸入文件
    const char *out = env->GetStringUTFChars(path_, NULL);
    const char* other = env->GetStringUTFChars(other_,NULL);
//    //寫入文件
    FILE *file_out_dcm = fopen(out, "wb+");
    //注冊輸入輸出組件
    av_register_all();

    for (int i = 0; i < len; i++) {
        jstring str = (jstring) env->GetObjectArrayElement(paths_, i);
        const char *path = env->GetStringUTFChars(str, 0);
        LOG_I(path);
        //解碼拼接
        decodeAudio(file_out_dcm, path);
        env->ReleaseStringUTFChars(str, path);
    }
    fclose(file_out_dcm);
    env->ReleaseStringUTFChars(path_, out);
    env->ReleaseStringUTFChars(other_,other);
    av_packet_free(&packet);
    if(out_buffer != NULL)
    av_freep(out_buffer);
    avformat_close_input(&av_fm_ctx);
    avformat_free_context(av_fm_ctx);
    //編碼
    encoder(out,other);
}

/**
 * 音頻解碼
 * @param out 輸出文件
 * @param path 解碼的文件地址
 */
void decodeAudio(FILE *out, const char *path) {
    av_fm_ctx = avformat_alloc_context();
    int av_fm_open_result = avformat_open_input(&av_fm_ctx, path, NULL, NULL);
    if (av_fm_open_result != 0) {
        LOG_I("打開失敗!");
        return;
    }
    //獲取音頻文件信息
    if (avformat_find_stream_info(av_fm_ctx, NULL) < 0) {
        LOG_I("獲取信息失敗");
        return;
    }
    //查找音頻解碼器
    //1.找到音頻流索引位置
    int audio_stream_index = -1;
    for (int i = 0; i < av_fm_ctx->nb_streams; i++) {
        //查找音頻流索引位置
        if (av_fm_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
            audio_stream_index = I;
            break;
        }
    }
    //判斷是否存在音頻流
    if (audio_stream_index == -1) {
        LOG_I("沒有這個(gè)音頻流!");
        return;
    }
    //獲取編碼器上下文(獲取編碼器ID)
    av_codec_pm = av_fm_ctx->streams[audio_stream_index]->codecpar;

    //獲取解碼器(根據(jù)編碼器的ID景埃,找到對應(yīng)的解碼器)
    av_codec = avcodec_find_decoder(av_codec_pm->codec_id);
    //打開解碼器
    av_codec_ctx = avcodec_alloc_context3(av_codec);
    //根據(jù)所提供的編解碼器的值填充編譯碼上下文
    int avcodec_to_context = avcodec_parameters_to_context(av_codec_ctx,av_codec_pm);
    if(avcodec_to_context < 0){
        return;
    }
    int av_codec_open_result = avcodec_open2(av_codec_ctx, av_codec, NULL);
    if (av_codec_open_result != 0) {
        LOG_I("解碼器打開失敗!");
        return;
    }
    //從輸入文件讀取一幀壓縮數(shù)據(jù)
    //循環(huán)遍歷
    //保存一幀讀取的壓縮數(shù)據(jù)-(提供緩沖區(qū))
        packet = (AVPacket *) av_malloc(sizeof(AVPacket));
    //內(nèi)存分配
        in_frame = av_frame_alloc();
    //定義上下文(開辟內(nèi)存)
        swr_ctx = swr_alloc();
    //設(shè)置音頻采樣上下文參數(shù)(例如:碼率媒至、采樣率、采樣格式谷徙、輸出聲道等等......)
    //swr_alloc_set_opts參數(shù)分析如下
    //參數(shù)一:音頻采樣上下文
    //參數(shù)二:輸出聲道布局(例如:立體拒啰、環(huán)繞等等......)
    //立體聲
    uint64_t out_ch_layout = AV_CH_LAYOUT_STEREO;
    //參數(shù)三:輸出音頻采樣格式(采樣精度)
    AVSampleFormat av_sm_fm = AV_SAMPLE_FMT_S16;
    //參數(shù)四:輸出音頻采樣率(例如:44100Hz、48000Hz等等......)
    //在這里需要注意:保證輸出采樣率和輸入的采樣率保證一直(如果你不想一直完慧,你可進(jìn)行采樣率轉(zhuǎn)換)
    int out_sample_rate = av_codec_ctx->sample_rate;
    //參數(shù)五:輸入聲道布局
    int64_t in_ch_layout = av_get_default_channel_layout(av_codec_ctx->channels);
    //參數(shù)六:輸入音頻采樣格式(采樣精度)
    //參數(shù)七:輸入音頻采樣率(例如:44100Hz图呢、48000Hz等等......)
    //參數(shù)八:偏移量
    //參數(shù)九:日志統(tǒng)計(jì)上下文
    swr_alloc_set_opts(swr_ctx,
                       out_ch_layout,
                       av_sm_fm,
                       out_sample_rate,
                       in_ch_layout,
                       av_codec_ctx->sample_fmt,
                       av_codec_ctx->sample_rate,
                       0,
                       NULL);
    //初始化音頻采樣數(shù)據(jù)上下文
    swr_init(swr_ctx);
    //音頻采樣數(shù)據(jù)緩沖區(qū)(每一幀大小)
    //44100 16bit  大小: size = 44100 * 2 / 1024 = 86KB
    //最大采樣率
        out_buffer = (uint8_t *) av_malloc(MAX_AUDIO_FRAME_SIZE);
    //獲取輸出聲道數(shù)量(根據(jù)聲道布局獲取對應(yīng)的聲道數(shù)量)
    int out_nb_channels = av_get_channel_layout_nb_channels(out_ch_layout);
    //大于等于0,繼續(xù)讀取骗随,小于0說明讀取完畢或者讀取失敗
    int ret, index = 0;
    while (av_read_frame(av_fm_ctx, packet) >= 0) {
        //解碼一幀音頻壓縮數(shù)據(jù)得到音頻采樣數(shù)據(jù)
        if (packet->stream_index == audio_stream_index) {
            //7.解碼一幀音頻壓縮數(shù)據(jù)蛤织,得到一幀音頻采樣數(shù)據(jù)
            //0:表示成功(成功解壓一幀音頻壓縮數(shù)據(jù))
            //AVERROR(EAGAIN): 現(xiàn)在輸出數(shù)據(jù)不可用,可以嘗試發(fā)送一幀新的視頻壓縮數(shù)據(jù)(或者說嘗試解壓下一幀視頻壓縮數(shù)據(jù))
            //AVERROR_EOF:解碼完成鸿染,沒有新的視頻壓縮數(shù)據(jù)
            //AVERROR(EINVAL):當(dāng)前是一個(gè)編碼器指蚜,但是編解碼器未打開
            //AVERROR(ENOMEM):解碼一幀視頻壓縮數(shù)據(jù)發(fā)生異常
            avcodec_send_packet(av_codec_ctx, packet);
            //返回值解釋:
            //0:表示成功(成功獲取一幀音頻采樣數(shù)據(jù))
            //AVERROR(EAGAIN): 現(xiàn)在輸出數(shù)據(jù)不可用,可以嘗試接受一幀新的視頻像素?cái)?shù)據(jù)(或者說嘗試獲取下一幀視頻像素?cái)?shù)據(jù))
            //AVERROR_EOF:接收完成涨椒,沒有新的視頻像素?cái)?shù)據(jù)了
            //AVERROR(EINVAL):當(dāng)前是一個(gè)編碼器摊鸡,但是編解碼器未打開
            ret = avcodec_receive_frame(av_codec_ctx, in_frame);
            if (ret == 0) {
                //將音頻采樣數(shù)據(jù)保存(寫入到文件中)
                //音頻采樣數(shù)據(jù)格式是:PCM格式、采樣率(44100Hz)蚕冬、16bit
                //對音頻采樣數(shù)據(jù)進(jìn)行轉(zhuǎn)換為PCM格式
                //參數(shù)一:音頻采樣上下文
                //參數(shù)二:輸出音頻采樣緩沖區(qū)
                //參數(shù)三:輸出緩沖區(qū)大小
                //參數(shù)四:輸入音頻采樣數(shù)據(jù)
                //參數(shù)五:輸入音頻采樣數(shù)據(jù)大小
                swr_convert(swr_ctx,
                            &out_buffer,
                            MAX_AUDIO_FRAME_SIZE,
                            (const uint8_t **) in_frame->data, in_frame->nb_samples);

                //獲取緩沖區(qū)實(shí)際數(shù)據(jù)大小
                //參數(shù)一:行大小
                //參數(shù)二:輸出聲道個(gè)數(shù)
                //參數(shù)三:輸入的大小
                //參數(shù)四:輸出的音頻采樣數(shù)據(jù)格式
                //參數(shù)五:字節(jié)對齊
               int out_buffer_size = av_samples_get_buffer_size(NULL,
              out_nb_channels,in_frame->nb_samples,av_sm_fm, 1);
                //寫入到文件中
                fwrite(out_buffer, 1, (size_t) out_buffer_size, out);
                LOG_I_ARGS("音頻幀:%d\n", ++index);
            }
        }
    }
    swr_close(swr_ctx);
    swr_free(&swr_ctx);
    av_frame_free(&in_frame);
    avcodec_parameters_free(&av_codec_pm);
    avcodec_close(av_codec_ctx);
    avcodec_free_context(&av_codec_ctx);
}

/**
 * 音頻編碼
 * @param path PCM文件地址
 * @param out 輸出文件地址
 */
void encoder(const char* path,const char* out){
    //打開 pcm,MP3文件
    FILE* fpcm = fopen(path,"rb");
    FILE* fmp3 = fopen(out,"wb");
    short int pcm_buffer[8192*2];
    unsigned char mp3_buffer[8192];
    //初始化lame的編碼器
    lame_t lame =  lame_init();
    //設(shè)置lame mp3編碼的采樣率
    lame_set_in_samplerate(lame , 44100);
    lame_set_num_channels(lame,2);
    //設(shè)置MP3的編碼方式
    lame_set_VBR(lame, vbr_default);
    lame_init_params(lame);
    LOG_I("lame init finish");
    int read ; int write; //代表讀了多少個(gè)次 和寫了多少次
    int total=0; // 當(dāng)前讀的wav文件的byte數(shù)目
    do{
        read = fread(pcm_buffer,sizeof(short int)*2, 8192,fpcm);
        total +=  read* sizeof(short int)*2;
        LOG_I_ARGS("converting ....%d", total);

        // 調(diào)用java代碼 完成進(jìn)度條的更新
        if(read!=0){
            write = lame_encode_buffer_interleaved(lame,pcm_buffer,read,mp3_buffer,8192);
            //把轉(zhuǎn)化后的mp3數(shù)據(jù)寫到文件里
            fwrite(mp3_buffer,sizeof(unsigned char),write,fmp3);
        }
        if(read==0){
            lame_encode_flush(lame,mp3_buffer,8192);
        }
    }while(read!=0);
    LOG_I("convert  finish");
    lame_close(lame);
    fclose(fpcm);
    fclose(fmp3);
}

  static {
        System.loadLibrary("native-lib");
    }
   /**
     * 拼接音頻
     * @param paths 音頻地址集合
     * @param path 采樣數(shù)據(jù)地址
     * @param out 編碼數(shù)據(jù)地址
     */  
 public native void jointAudio(String[]paths,String path,String out);
 
  public void jointAudioClick(View view) {
        List<String> audioList = new ArrayList<String>();
        audioList.add(path+"0.mp3");
        audioList.add(path+"1.wav");
        audioList.add(path+"2.aac");
        new Thread(new Runnable() {
                @Override
                public void run() { 
            jointAudio(finalPaths,target,path+"eng100.mp3");  
                }
            }).start();
            }

第二種情況免猾,相同格式音頻拼接,只需要字節(jié)流拼接即可囤热,當(dāng)然如果不嫌效率低也可以選用以上兩種方式進(jìn)行拼接猎提。

 public void jointAudio(String audioPath, String toPath)throws Exception {
        File audioFile = new File(audioPath);
        File toFile = new File(toPath);
        FileInputStream in=new FileInputStream(audioFile);
        FileOutputStream out=new FileOutputStream(toFile,true);

        byte bs[]=new byte[1024*4];
        int len=0;
        //先讀第一個(gè)
        while((len=in.read(bs))!=-1){
            out.write(bs,0,len);
        }
        in.close();
        out.close();
    }
 public void jointAudioClick(View view) {
        List<String> audioList = new ArrayList<String>();
        audioList.add(path+"0.mp3");
        audioList.add(path+"1.mp3");
        audioList.add(path+"2.mp3");
        new Thread(new Runnable() {
                @Override
                public void run() { 
            try {
               for (String audioPath : audioList) {
                  //拼接
                  jointAudio(audioPath, path + "eng100100.mp3");
                  }catch (Exception ex){
                    ex.printStackTrace();
                  }
                }
            }).start();
            }

本文章著作版權(quán)所屬:微笑面對,請關(guān)注我的CSDN博客:博客地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市旁蔼,隨后出現(xiàn)的幾起案子锨苏,更是在濱河造成了極大的恐慌,老刑警劉巖棺聊,帶你破解...
    沈念sama閱讀 222,807評論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件伞租,死亡現(xiàn)場離奇詭異,居然都是意外死亡限佩,警方通過查閱死者的電腦和手機(jī)葵诈,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,284評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來祟同,“玉大人作喘,你說我怎么就攤上這事∧涂鳎” “怎么了徊都?”我有些...
    開封第一講書人閱讀 169,589評論 0 363
  • 文/不壞的土叔 我叫張陵沪斟,是天一觀的道長广辰。 經(jīng)常有香客問我暇矫,道長,這世上最難降的妖魔是什么择吊? 我笑而不...
    開封第一講書人閱讀 60,188評論 1 300
  • 正文 為了忘掉前任李根,我火速辦了婚禮,結(jié)果婚禮上几睛,老公的妹妹穿的比我還像新娘房轿。我一直安慰自己,他們只是感情好所森,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,185評論 6 398
  • 文/花漫 我一把揭開白布囱持。 她就那樣靜靜地躺著,像睡著了一般焕济。 火紅的嫁衣襯著肌膚如雪纷妆。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,785評論 1 314
  • 那天晴弃,我揣著相機(jī)與錄音掩幢,去河邊找鬼。 笑死上鞠,一個(gè)胖子當(dāng)著我的面吹牛际邻,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播芍阎,決...
    沈念sama閱讀 41,220評論 3 423
  • 文/蒼蘭香墨 我猛地睜開眼世曾,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了谴咸?” 一聲冷哼從身側(cè)響起度硝,我...
    開封第一講書人閱讀 40,167評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎寿冕,沒想到半個(gè)月后蕊程,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,698評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡驼唱,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,767評論 3 343
  • 正文 我和宋清朗相戀三年藻茂,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片玫恳。...
    茶點(diǎn)故事閱讀 40,912評論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡辨赐,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出京办,到底是詐尸還是另有隱情掀序,我是刑警寧澤,帶...
    沈念sama閱讀 36,572評論 5 351
  • 正文 年R本政府宣布惭婿,位于F島的核電站不恭,受9級特大地震影響叶雹,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜换吧,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,254評論 3 336
  • 文/蒙蒙 一折晦、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧沾瓦,春花似錦满着、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,746評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至缕探,卻和暖如春响驴,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背撕蔼。 一陣腳步聲響...
    開封第一講書人閱讀 33,859評論 1 274
  • 我被黑心中介騙來泰國打工豁鲤, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人鲸沮。 一個(gè)月前我還...
    沈念sama閱讀 49,359評論 3 379
  • 正文 我出身青樓琳骡,卻偏偏與公主長得像,于是被迫代替她去往敵國和親讼溺。 傳聞我的和親對象是個(gè)殘疾皇子楣号,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,922評論 2 361