編輯:關於 Android 程式設計
下面的代碼不包含播放環節,但錄音與封裝的部分寫得比較完整,也順帶把原理講清楚。
// 音頻獲取源 private int audioSource = MediaRecorder.AudioSource.MIC; // 採樣率,44100 是目前的標準,但部分設備只支持 22050、16000、11025 private static int sampleRateInHz = 44100; // 聲道:CHANNEL_IN_STEREO 為雙聲道,CHANNEL_IN_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 static final String AudioName = "/sdcard/love.raw"; // 可播放的音頻文件 private static final String NewAudioName = "/sdcard/new.wav";
採樣率這一項要特別小心。44100 雖然是慣例,但設備支持情況參差不齊,比較穩妥的做法是依次嘗試一組候選值,用 AudioRecord.getMinBufferSize() 的返回值判斷哪個可用,而不是硬寫死。
private void creatAudioRecord() {
// 查詢該參數組合下的最小緩衝區大小
bufferSizeInBytes = AudioRecord.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat);
audioRecord = new AudioRecord(audioSource, sampleRateInHz,
channelConfig, audioFormat, bufferSizeInBytes);
}
private void startRecord() {
audioRecord.startRecording();
isRecord = true;
// 開線程寫文件,避免阻塞 UI
new Thread(new AudioRecordThread()).start();
}
private void close() {
if (audioRecord != null) {
isRecord = false; // 先停寫入循環
audioRecord.stop();
audioRecord.release(); // 釋放底層資源,這步不能省
audioRecord = null;
}
}
class AudioRecordThread implements Runnable {
@Override
public void run() {
writeDateTOFile(); // 寫入裸數據
copyWaveFile(AudioName, NewAudioName); // 加上頭文件
}
}
release() 這一步经常被遺忘,漏掉會導致麥克風資源遲遲不釋放,後續再次錄音可能直接失敗。
private void writeDateTOFile() {
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);
if (AudioRecord.ERROR_INVALID_OPERATION != readsize) {
try {
fos.write(audiodata);
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
這裡寫出來的文件是不能直接播放的——AudioRecord 拿到的是原始裸 PCM 數據,沒有任何頭信息。但這恰恰是它的價值所在:拿到裸數據意味著你可以隨意加工。比如做「說話的湯姆貓」,正是在這一層做變調處理,然後重新封裝。做音效、做實時波形、做自定義編碼,都從這裡開始。
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 (Exception e) {
e.printStackTrace();
}
}
頭信息一共 44 個字節。為什麼是 44?這個格式規定如此。你隨便找一個 wav 文件用十六進制打開,都會看到開頭這一段幾乎一模一樣——RIFF/WAVE 這套容器格式,每種文件格式都有自己的專屬頭。
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; // fmt chunk 大小
header[17] = 0;
header[18] = 0;
header[19] = 0;
header[20] = 1; // format = 1,PCM
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'; // 'data' chunk
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);
}
整段頭信息的結構其實就是 RIFF 容器規範的直譯:12 字節的 RIFF/WAVE 標識,24 字節的 fmt 子塊(描述編碼格式、聲道數、採樣率、位寬),再加 8 字節的 data 子塊頭與長度。所有多字節數值都是小端序,所以每個都要拆成 4 個字節反向寫入。
最後在 onDestroy() 裡記得調用 close() 收尾,否則麥克風會一直被佔著。
打造專屬客製化 Dialog:Builder 模式搭配工具類的完整實作
做 Android 開發時,你一定遇過這個困擾:系統低版本的 Dialog 樣式老氣又醜,高版本雖然美觀一些,卻仍與公司 UI 設計師提供的效果圖有段距離。既然預設樣式滿
Volley 深度實戰:從 Request 到自訂框架封裝
Volley 是 Google 在 I/O 2013 端出的官方網路通訊庫。在它出現之前,Android 開發者多半在幾個成熟的三方庫之間做選擇——android-asy
Visual Studio 2015 安裝卡在 Android SDK(API 19 與 21)的解法
問題描述 安裝 Visual Studio 2015 時,進度停在「Android SDK 設置(API 級別 19 和 21)」這一關,長時間沒有動靜,裝不下去也退不
GridView 實現帶分割線的九宮格:兩種方案對比
ListView 想加分割線很簡單,布局裡寫 android:divider 和 android:dividerHeight 就行。GridView 沒有這兩個屬性,需要