第一種情況:不同壓縮格式音頻拼接,不同的壓縮格式拼接需要解碼為采樣數(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();
}