音频混音处理
2020-12-14 本文已影响0人
梅芳姑
统一通道数和采样率
参考文章 详解如何使用代码进行音频合成
不过,上面给的代码中也有不对的地方(应该是采样点字节数那里),不能全抄。
混音算法
/**
* 按音量权值进行混音算法
*/
private static class WeightAudioMixer extends MultiAudioMixer {
float weight[];
public WeightAudioMixer(float[] weight) {
this.weight = weight;
}
@Override
public byte[] mixRawAudioBytes(byte[][] bMulRoadAudioes) {
if (bMulRoadAudioes == null || bMulRoadAudioes.length == 0)
return null;
byte[] realMixAudio = bMulRoadAudioes[0];
if (bMulRoadAudioes.length == 1) {
DLog.i("MultiAudioMixer", "bMulRoadAudioes.length == 1");
return realMixAudio;
}
for (int rw = 0; rw < bMulRoadAudioes.length; ++rw) {
if (bMulRoadAudioes[rw].length != realMixAudio.length) {
Log.e("app", "column of the road of audio + " + rw + " is diffrent.");
return null;
}
}
int row = bMulRoadAudioes.length;
int coloum = realMixAudio.length / 2;
short[][] sMulRoadAudioes = new short[row][coloum];
for (int r = 0; r < row; ++r) {
for (int c = 0; c < coloum; ++c) {
sMulRoadAudioes[r][c] = (short) ((bMulRoadAudioes[r][c * 2] & 0xff) | (bMulRoadAudioes[r][c * 2 + 1] & 0xff) << 8);
//todo
// if(r==0){
// sMulRoadAudioes[r][c]=(short) (sMulRoadAudioes[r][c]*firstweight);
// }else if(r==1){
// sMulRoadAudioes[r][c]=(short) (sMulRoadAudioes[r][c]*secondweight);
// }
}
}
short[] sMixAudio = new short[coloum];
int mixVal;
int sr = 0;
for (int sc = 0; sc < coloum; ++sc) {
mixVal = 0;
sr = 0;
for (; sr < row; ++sr) {
//mixVal += sMulRoadAudioes[sr][sc];
mixVal += sMulRoadAudioes[sr][sc] * weight[sr];
DLog.i("MultiAudioMixer", "sMulRoadAudioes:" + sMulRoadAudioes[sr][sc] + "weight[" + sr + "]:" + weight[sr]);
}
// sMixAudio[sc] = (short) (mixVal / row);
sMixAudio[sc] = (short) (mixVal);
}
for (sr = 0; sr < coloum; ++sr) {
realMixAudio[sr * 2] = (byte) (sMixAudio[sr] & 0x00FF);
realMixAudio[sr * 2 + 1] = (byte) ((sMixAudio[sr] & 0xFF00) >> 8);
}
return realMixAudio;
}
}
配合上面那篇文章作者的demo :https://github.com/CrazyZty/ComposeAudio,基本可以实现背景音乐和视频原声音按音量混合的功能了