第一種情況:不同壓縮格式音頻拼接,不同的壓縮格式拼接需要解碼為采樣資料然後拼接,然後再編碼為統一的壓縮格式。 方法一:FFmpeg指令拼接,ffmpeg -I ‘concat:0.mp3|1.wav|2.aac’ -acodec copy merge.mp3。(注意:這種方式,速度相對還可以,但是在android裝置上一下子拼接6個音頻以上就會奔潰,應該是C代碼中有什麼變量沒有釋放掉)
static {
System.loadLibrary("MyLib");
}
public native void command(int len,String[] argv);
/**
* 使用ffmpeg指令行進行音頻合并
* @param src 源檔案
* @param targetFile 目标檔案
* @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(" ");//以空格分割為字元串數組
}
/**
* 拼接音頻
* @param paths 音頻位址集合
* @return 音頻拼接之後的位址
*/
private String jointAudio1(List<String> paths) {
String path = "";
for (int i = ; i < paths.size(); i++) {
String[] pathArr = new String[];
if (i==) {
pathArr[] = paths.get(i - );
pathArr[] = paths.get(i);
}else{
pathArr[] = path;
pathArr[] = paths.get(i);
}
File file = new File(paths.get());
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);
//視訊轉碼壓縮主函數入口
//ffmpeg_mod.c有一個FFmpeg視訊轉碼主函數入口
// argc = str.split(" ").length()
// argv = str.split(" ") 字元串數組
//參數一:指令行字元串指令個數
//參數二:指令行字元串數組
int ffmpegmain(int argc, char **argv);
JNIEXPORT void JNICALL Java_com_xy_openndk_audiojointdemo_FFmpegLib_command
(JNIEnv *env, jobject jobj,jint jlen,jobjectArray jobjArray){
//轉碼
//将java的字元串數組轉成C字元串
int argc = jlen;
//開辟記憶體空間
char **argv = (char**)malloc(sizeof(char*) * argc);
//填充内容
for (int i = ; i < argc; ++i) {
jstring str = (*env)->GetObjectArrayElement(env,jobjArray,i);
const char* tem = (*env)->GetStringUTFChars(env,str,);
argv[i] = (char*)malloc(sizeof(char)*);
strcpy(argv[i],tem);
(*env)->ReleaseStringUTFChars(env,str,tem);
}
//開始轉碼(底層實作就是隻需指令)
ffmpegmain(argc,argv);
//釋放記憶體空間
for (int i = ; i < argc; ++i) {
free(argv[i]);
}
//釋放數組
free(argv);
}
方法二:FFmpeg解碼為采樣資料之後拼接采樣資料,然後再編碼為壓縮格式資料。這裡我選用了FFmpeg進行編解碼,當然也可以選擇Android系統提供的MediaCodec進行解碼拼接再編碼。(注意:這種方式速度很慢很慢的,但這種方式是最安全科學的做法。)
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,);
#define MAX_AUDIO_FRAME_SIZE ()
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 拼接的采樣資料檔案
* @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 = ; i < len; i++) {
jstring str = (jstring) env->GetObjectArrayElement(paths_, i);
const char *path = env->GetStringUTFChars(str, );
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 != ) {
LOG_I("打開失敗!");
return;
}
//擷取音頻檔案資訊
if (avformat_find_stream_info(av_fm_ctx, NULL) < ) {
LOG_I("擷取資訊失敗");
return;
}
//查找音頻解碼器
//找到音頻流索引位置
int audio_stream_index = -;
for (int i = ; 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 == -) {
LOG_I("沒有這個音頻流!");
return;
}
//擷取編碼器上下文(擷取編碼器ID)
av_codec_pm = av_fm_ctx->streams[audio_stream_index]->codecpar;
//擷取解碼器(根據編碼器的ID,找到對應的解碼器)
av_codec = avcodec_find_decoder(av_codec_pm->codec_id);
//打開解碼器
av_codec_ctx = avcodec_alloc_context3(av_codec);
//根據所提供的編解碼器的值填充編譯碼上下文
int avcodec_to_context = avcodec_parameters_to_context(av_codec_ctx,av_codec_pm);
if(avcodec_to_context < ){
return;
}
int av_codec_open_result = avcodec_open2(av_codec_ctx, av_codec, NULL);
if (av_codec_open_result != ) {
LOG_I("解碼器打開失敗!");
return;
}
//從輸入檔案讀取一幀壓縮資料
//循環周遊
//儲存一幀讀取的壓縮資料-(提供緩沖區)
packet = (AVPacket *) av_malloc(sizeof(AVPacket));
//記憶體配置設定
in_frame = av_frame_alloc();
//定義上下文(開辟記憶體)
swr_ctx = swr_alloc();
//設定音頻采樣上下文參數(例如:碼率、采樣率、采樣格式、輸出聲道等等......)
//swr_alloc_set_opts參數分析如下
//參數一:音頻采樣上下文
//參數二:輸出聲道布局(例如:立體、環繞等等......)
//立體聲
uint64_t out_ch_layout = AV_CH_LAYOUT_STEREO;
//參數三:輸出音頻采樣格式(采樣精度)
AVSampleFormat av_sm_fm = AV_SAMPLE_FMT_S16;
//參數四:輸出音頻采樣率(例如:44100Hz、48000Hz等等......)
//在這裡需要注意:保證輸出采樣率和輸入的采樣率保證一直(如果你不想一直,你可進行采樣率轉換)
int out_sample_rate = av_codec_ctx->sample_rate;
//輸入聲道布局
int64_t in_ch_layout = av_get_default_channel_layout(av_codec_ctx->channels);
//參數六:輸入音頻采樣格式(采樣精度)
//參數七:輸入音頻采樣率(例如:44100Hz、48000Hz等等......)
//參數八:偏移量
//參數九:日志統計上下文
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,
,
NULL);
//初始化音頻采樣資料上下文
swr_init(swr_ctx);
//音頻采樣資料緩沖區(每一幀大小)
//44100 16bit 大小: size = 44100 * 2 / 1024 = 86KB
//最大采樣率
out_buffer = (uint8_t *) av_malloc(MAX_AUDIO_FRAME_SIZE);
//擷取輸出聲道數量(根據聲道布局擷取對應的聲道數量)
int out_nb_channels = av_get_channel_layout_nb_channels(out_ch_layout);
//大于等于0,繼續讀取,小于0說明讀取完畢或者讀取失敗
int ret, index = ;
while (av_read_frame(av_fm_ctx, packet) >= ) {
//解碼一幀音頻壓縮資料得到音頻采樣資料
if (packet->stream_index == audio_stream_index) {
//解碼一幀音頻壓縮資料,得到一幀音頻采樣資料
//0:表示成功(成功解壓一幀音頻壓縮資料)
//AVERROR(EAGAIN): 現在輸出資料不可用,可以嘗試發送一幀新的視訊壓縮資料(或者說嘗試解壓下一幀視訊壓縮資料)
//AVERROR_EOF:解碼完成,沒有新的視訊壓縮資料
//AVERROR(EINVAL):目前是一個編碼器,但是編解碼器未打開
//AVERROR(ENOMEM):解碼一幀視訊壓縮資料發生異常
avcodec_send_packet(av_codec_ctx, packet);
//傳回值解釋:
//0:表示成功(成功擷取一幀音頻采樣資料)
//AVERROR(EAGAIN): 現在輸出資料不可用,可以嘗試接受一幀新的視訊像素資料(或者說嘗試擷取下一幀視訊像素資料)
//AVERROR_EOF:接收完成,沒有新的視訊像素資料了
//AVERROR(EINVAL):目前是一個編碼器,但是編解碼器未打開
ret = avcodec_receive_frame(av_codec_ctx, in_frame);
if (ret == ) {
//将音頻采樣資料儲存(寫入到檔案中)
//音頻采樣資料格式是:PCM格式、采樣率(44100Hz)、16bit
//對音頻采樣資料進行轉換為PCM格式
//參數一:音頻采樣上下文
//參數二:輸出音頻采樣緩沖區
//參數三:輸出緩沖區大小
//參數四:輸入音頻采樣資料
//參數五:輸入音頻采樣資料大小
swr_convert(swr_ctx,
&out_buffer,
MAX_AUDIO_FRAME_SIZE,
(const uint8_t **) in_frame->data, in_frame->nb_samples);
//擷取緩沖區實際資料大小
//參數一:行大小
//參數二:輸出聲道個數
//參數三:輸入的大小
//參數四:輸出的音頻采樣資料格式
//參數五:位元組對齊
int out_buffer_size = av_samples_get_buffer_size(NULL,
out_nb_channels,in_frame->nb_samples,av_sm_fm, );
//寫入到檔案中
fwrite(out_buffer, , (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[*];
unsigned char mp3_buffer[];
//初始化lame的編碼器
lame_t lame = lame_init();
//設定lame mp3編碼的采樣率
lame_set_in_samplerate(lame , );
lame_set_num_channels(lame,);
//設定MP3的編碼方式
lame_set_VBR(lame, vbr_default);
lame_init_params(lame);
LOG_I("lame init finish");
int read ; int write; //代表讀了多少個次 和寫了多少次
int total=; // 目前讀的wav檔案的byte數目
do{
read = fread(pcm_buffer,sizeof(short int)*, ,fpcm);
total += read* sizeof(short int)*;
LOG_I_ARGS("converting ....%d", total);
// 調用java代碼 完成進度條的更新
if(read!=){
write = lame_encode_buffer_interleaved(lame,pcm_buffer,read,mp3_buffer,);
//把轉化後的mp3資料寫到檔案裡
fwrite(mp3_buffer,sizeof(unsigned char),write,fmp3);
}
if(read==){
lame_encode_flush(lame,mp3_buffer,);
}
}while(read!=);
LOG_I("convert finish");
lame_close(lame);
fclose(fpcm);
fclose(fmp3);
}
static {
System.loadLibrary("native-lib");
}
/**
* 拼接音頻
* @param paths 音頻位址集合
* @param path 采樣資料位址
* @param out 編碼資料位址
*/
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();
}
第二種情況,相同格式音頻拼接,隻需要位元組流拼接即可,當然如果不嫌效率低也可以選用以上兩種方式進行拼接。(注意:音頻的聲道數需要一緻,我開發遇到把單聲道和立體聲拼接到一塊,會使得音頻時間成倍增加,各位請注意。)
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[*];
int len=;
//先讀第一個
while((len=in.read(bs))!=-){
out.write(bs,,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();
}
本文章著作版權所屬:微笑面對,請關注我的CSDN部落格:部落格位址