?? 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(\); ??? isRecord = false;//停止文件写入 ??? audioRecord.stop();
??? audioRecord.release();//释放资源 ??? audioRecord = null; ??? } ??? } ???
??? class AudioRecordThread implements Runnable {
??? @Override ??? public void run() {
??? writeDateTOFile();//往文件中写入裸数据
??? copyWaveFile(AudioName, NewAudioName);//给裸数据加上头
文件
??? } ??? } ??? ??? /**
??? * 这里将数据写入文件,但是并不能播放,因为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); ??? if (AudioRecord.ERROR_INVALID_OPERATION != readsize) { ??? try {
??? fos.write(audiodata); ??? } catch (IOException e) { ??? e.printStackTrace(); ??? } ??? } ??? } ??? try {
??? fos.close();// 关闭写入流 ??? } catch (IOException e) { ??? e.printStackTrace();
??? } ??? } ???
??? // 这里得到可播放的音频文件
??? 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);