需求背景:
博主目前所在的公司是一家做視頻通訊的公司,所以對音頻,視頻這一塊對編碼方式都有一定的要求,由於之前一直沒有接觸JNI這一塊,突然讓我去做音頻的轉碼還是有一定的苦難的。一開始對於JNI編程我是拒絕的,一直遵循着能用java源碼,就絕不用Jni那一塊。但是,顯示總是殘酷的,網上的資料,Demo很少,或者都是年代久遠,還不能運行的。所以我抱着試一試的心態去接觸JNI,也還蠻有收穫的,好了廢話了這麼多,也該進入主題了。
Demo主要功能:
AndroidStudio項目,在安卓平臺下,調用G.711 C++編解碼方法進行音頻源的編碼和解碼。Demo在文章末尾。
G.711 C++源碼
http://download.csdn.net/download/orient1860/7691041 待會我demo裏面也有
Android 源碼
package com.chezi008.hellojni.encode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.PixelFormat;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import com.chezi008.hellojni.R;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 描述:G.711 編碼與解碼
* 作者:chezi008 on 2017/3/10 16:33
* 郵箱:[email protected]
*/
@SuppressLint("SdCardPath")
public class G711DecoderActivity extends Activity {
// 音頻獲取源
private int audioSource = MediaRecorder.AudioSource.MIC;
// 設置音頻採樣率,44100是目前的標準,但是某些設備仍然支持22050,16000,11025
private static int sampleRateInHz = 8000;
// 設置音頻的錄製的聲道CHANNEL_I N_STEREO爲雙聲道,CHANNEL_CONFIGURATION_MONO爲單聲道
private static int channelConfig = AudioFormat.CHANNEL_IN_STEREO;
// 音頻數據格式:PCM 16位每個樣本。保證設備支持。PCM 8位每個樣本。不一定能得到設備支持。
private static int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
// 緩衝區字節大小
private int bufferSizeInBytes = 0;
private Button Start;
private Button Stop;
private Button convert;
private AudioRecord audioRecord;
private boolean isRecord = false;// 設置正在錄製的狀態
//AudioName裸音頻數據文件,編碼後的文件
private static final String AudioName = "/sdcard/end.g711";
//解碼後的文件
private static final String AudioDecodeName = "/sdcard/endDecode.g711";
//NewAudioName可播放的音頻文件
private static final String NewAudioName = "/sdcard/new.wav";
private G711Decoder codec;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFormat(PixelFormat.TRANSLUCENT);// 讓界面橫屏
requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉界面標題
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// 重新設置界面大小
setContentView(R.layout.activity_g711);
init();
}
private void init() {
Start = (Button) this.findViewById(R.id.start);
Stop = (Button) this.findViewById(R.id.stop);
convert = (Button) findViewById(R.id.convert);
Start.setOnClickListener(new TestAudioListener());
Stop.setOnClickListener(new TestAudioListener());
convert.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// new PlayTask().execute();
new Thread(new AudioConvert()).start();
}
});
codec = new G711Decoder();
creatAudioRecord();
}
private void creatAudioRecord() {
// 獲得緩衝區字節大小
bufferSizeInBytes = AudioRecord.getMinBufferSize(sampleRateInHz,
channelConfig, audioFormat);
// 創建AudioRecord對象
audioRecord = new AudioRecord(audioSource, sampleRateInHz,
channelConfig, audioFormat, bufferSizeInBytes);
}
class TestAudioListener implements OnClickListener {
@Override
public void onClick(View v) {
if (v == Start) {
startRecord();
}
if (v == Stop) {
stopRecord();
}
}
}
private void startRecord() {
audioRecord.startRecording();
// 讓錄製狀態爲true
isRecord = true;
// 開啓音頻文件寫入線程
new Thread(new AudioRecordThread()).start();
}
private void stopRecord() {
close();
}
private void close() {
if (audioRecord != null) {
System.out.println("stopRecord");
isRecord = false;//停止文件寫入
audioRecord.stop();
audioRecord.release();//釋放資源
audioRecord = null;
}
}
class AudioRecordThread implements Runnable {
@Override
public void run() {
writeDateTOFile();//往文件中寫入裸數據
// copyWaveFile(AudioName, NewAudioName);//給裸數據加上頭文件
}
}
class AudioConvert implements Runnable {
@Override
public void run() {
decodeAudio(AudioName, AudioDecodeName);
copyWaveFile(AudioDecodeName, NewAudioName);//給裸數據加上頭文件
}
}
/**
* 解碼音頻文件
* @param inFilename
* @param outFilename
*/
private void decodeAudio(String inFilename, String outFilename) {
FileInputStream in = null;
FileOutputStream out = null;
byte[] data = new byte[1024];
byte[] outData = new byte[2048];//這裏特別注意outData是data的兩倍,之前不知道,一直卡在這裏,是的解碼進行不下去
try {
in = new FileInputStream(inFilename);
out = new FileOutputStream(outFilename);
int length = 0;
while ((length = in.read(data)) != -1) {
codec.VoiceDecode(data, outData, length);
out.write(outData);
}
in.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 這裏將數據寫入文件,但是並不能播放,因爲AudioRecord獲得的音頻是原始的裸音頻,
* 如果需要播放就必須加入一些格式或者編碼的頭信息。但是這樣的好處就是你可以對音頻的 裸數據進行處理,比如你要做一個愛說話的TOM
* 貓在這裏就進行音頻的處理,然後重新封裝 所以說這樣得到的音頻比較容易做一些音頻的處理。
*/
private void writeDateTOFile() {
// new一個byte數組用來存一些字節數據,大小爲緩衝區大小
byte[] audiodata = new byte[bufferSizeInBytes];
FileOutputStream fos = null;
int readsize = 0;
try {
File file = new File(AudioName);
if (file.exists()) {
file.delete();
}
fos = new FileOutputStream(file);// 建立一個可存取字節的文件
} catch (Exception e) {
e.printStackTrace();
}
while (isRecord == true) {
readsize = audioRecord.read(audiodata, 0, bufferSizeInBytes);
byte[] alawData = new byte[readsize];
if (AudioRecord.ERROR_INVALID_OPERATION != readsize) {
try {
int len = codec.VoiceEncode(audiodata, alawData, readsize); //調用C代碼進行編碼
fos.write(alawData, 0, len); //保存到本地
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
fos.close();// 關閉寫入流
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 解碼後增加音頻文件的頭部,是的文件可播放
* @param inFilename
* @param outFilename
*/
private void copyWaveFile(String inFilename, String outFilename) {
FileInputStream in = null;
FileOutputStream out = null;
long totalAudioLen = 0;
long totalDataLen = totalAudioLen + 36;
long longSampleRate = sampleRateInHz;
int channels = 2;
long byteRate = 16 * sampleRateInHz * channels / 8;
byte[] data = new byte[bufferSizeInBytes];
try {
in = new FileInputStream(inFilename);
out = new FileOutputStream(outFilename);
totalAudioLen = in.getChannel().size();
totalDataLen = totalAudioLen + 36;
WriteWaveFileHeader(out, totalAudioLen, totalDataLen,
longSampleRate, channels, byteRate);
while (in.read(data) != -1) {
out.write(data);
}
in.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 這裏提供一個頭信息。插入這些信息就可以得到可以播放的文件。
* 爲我爲啥插入這44個字節,這個還真沒深入研究,不過你隨便打開一個wav
* 音頻的文件,可以發現前面的頭文件可以說基本一樣哦。每種格式的文件都有
* 自己特有的頭文件。
*/
private void WriteWaveFileHeader(FileOutputStream out, long totalAudioLen,
long totalDataLen, long longSampleRate, int channels, long byteRate)
throws IOException {
byte[] header = new byte[44];
header[0] = 'R'; // RIFF/WAVE header
header[1] = 'I';
header[2] = 'F';
header[3] = 'F';
header[4] = (byte) (totalDataLen & 0xff);
header[5] = (byte) ((totalDataLen >> 8) & 0xff);
header[6] = (byte) ((totalDataLen >> 16) & 0xff);
header[7] = (byte) ((totalDataLen >> 24) & 0xff);
header[8] = 'W';
header[9] = 'A';
header[10] = 'V';
header[11] = 'E';
header[12] = 'f'; // 'fmt ' chunk
header[13] = 'm';
header[14] = 't';
header[15] = ' ';
header[16] = 16; // 4 bytes: size of 'fmt ' chunk
header[17] = 0;
header[18] = 0;
header[19] = 0;
header[20] = 1; // format = 1
header[21] = 0;
header[22] = (byte) channels;
header[23] = 0;
header[24] = (byte) (longSampleRate & 0xff);
header[25] = (byte) ((longSampleRate >> 8) & 0xff);
header[26] = (byte) ((longSampleRate >> 16) & 0xff);
header[27] = (byte) ((longSampleRate >> 24) & 0xff);
header[28] = (byte) (byteRate & 0xff);
header[29] = (byte) ((byteRate >> 8) & 0xff);
header[30] = (byte) ((byteRate >> 16) & 0xff);
header[31] = (byte) ((byteRate >> 24) & 0xff);
header[32] = (byte) (2 * 16 / 8); // block align
header[33] = 0;
header[34] = 16; // bits per sample
header[35] = 0;
header[36] = 'd';
header[37] = 'a';
header[38] = 't';
header[39] = 'a';
header[40] = (byte) (totalAudioLen & 0xff);
header[41] = (byte) ((totalAudioLen >> 8) & 0xff);
header[42] = (byte) ((totalAudioLen >> 16) & 0xff);
header[43] = (byte) ((totalAudioLen >> 24) & 0xff);
out.write(header, 0, 44);
}
@Override
protected void onDestroy() {
close();
super.onDestroy();
}
}