因为项目中用到了阿里的语音识别技术,但是返回的是PCM原始数据,这里就需要将PCM转为AMR的音频格式,这里将其中遇到的问题记录下来,有需要的小伙伴们可以参考一下。
这里的实现思路先大致说一下,将PCM先转为WAV,然后再由WAV转为AMR。
话不多说,直接上代码。
我们先PCM转为WAV,要注意的是16k的PCM一定要对采样率进行向下采样成8kPCM之后,再将PCM进行转换成WAV,否则后面转出来的8k的AMR就一塌糊涂了!!!重新采样用的是三方库JSSRC,我这里是对JSSRCResampler进行了一些调整,直接将源码改成了16k转8k的。
public void pcmToWav(String inFilename, String outFilename, PcmToWavTransformListener listener) {
FileOutputStream out;
long totalAudioLen;//总录音长度
long totalDataLen;//总数据长度
long longSampleRate = 8000;
int channels = 1;
long byteRate = 8 * longSampleRate * channels / 8;
byte[] data = new byte[mBufferSize];
try {
FileInputStream inputStream = new FileInputStream(inFilename);
totalAudioLen = inputStream.getChannel().size();
//将16k的PCM进行重新的8k采样
JSSRCResampler in = new JSSRCResampler(inputStream);
//8k的PCM转为8k的WAV
out = new FileOutputStream(outFilename);
totalDataLen = totalAudioLen + 36;
writeWaveFileHeader(out, totalAudioLen, totalDataLen,
longSampleRate, channels, byteRate);
while (in.read(data) != -1) {
out.write(data);
out.flush();
}
Log.e(TAG, "pcmToWav: 停止处理");
in.close();
out.close();
if (listener != null) {
listener.transformFinish(outFilename);
}
} catch (IOException e) {
e.printStackTrace();
}
}
同采样率的8kWAV出来之后,下面就好办了,接下来我们用opencore-amr将WAV直接转换成需要的AMR,代码如下
public void wav2Amr(String inFilename, String outFilename, TransformListener listener) {
try {
FileInputStream inputStream = new FileInputStream(inFilename);
FileOutputStream outStream = new FileOutputStream(outFilename);
AmrEncoder.init(0);
List<short[]> armsList = new ArrayList<short[]>();
//写入Amr头文件
outStream.write(header);
int byteSize = 320;
byte[] buff = new byte[byteSize];
int rc = 0;
while ((rc = inputStream.read(buff, 0, byteSize)) > 0) {
short[] shortTemp = new short[160];
//将byte[]转换成short[]
ByteBuffer.wrap(buff).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shortTemp);
}
for (int i = 0; i < armsList.size(); i++) {
int size = armsList.get(i).length;
byte[] encodedData = new byte[size*2];
int len = AmrEncoder.encode(AmrEncoder.Mode.MR515.ordinal(), armsList.get(i), encodedData);
if (len>0) {
byte[] tempBuf = new byte[len];
System.arraycopy(encodedData, 0, tempBuf, 0, len);
outStream.write(tempBuf, 0, len);
}
}
outStream.close();
inputStream.close();
Log.e(TAG, "pcmToWav: amr生成完毕");
if (listener != null) {
listener.transformFinish(outFilename);
}
} catch (Exception e) {
e.printStackTrace();
}
}
到这里就得到了我们想要的AMR文件了。
https://github.com/hutm/JSSRC
https://github.com/kevinho/opencore-amr-android
|