本人公众号上线啦!!!
公众号与博客名一样:没有腹肌的程序猿
公众号文章类型:工作上所遇到的需求实现方案分享。
此外也会提供一些数据集供大家使用。(这个还在规划中,毕竟打工人时间挺紧的,哈哈哈哈)
到时候也会不定期给大家抽一些小东西哦。
Java将MP3文件转换成wav格式文件
(实操过,可以运行.)
<%
//将MP3文件转为wav文件
String filePath = "D:\\test.mp3";
String targetPath = "D:\\test.wav";
byteToWav(getBytes(filePath), targetPath);
%>
<%!
public static boolean byteToWav(byte[] sourceBytes, String targetPath){
if (sourceBytes == null || sourceBytes.length == 0) {
System.out.println("Illegal Argument passed to this method");
return false;
}
try (final ByteArrayInputStream bais = new ByteArrayInputStream(sourceBytes); final AudioInputStream sourceAIS = AudioSystem.getAudioInputStream(bais)) {
AudioFormat sourceFormat = sourceAIS.getFormat();
// 设置MP3的语音格式,并设置16bit
AudioFormat mp3tFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, sourceFormat.getSampleRate(), 16, sourceFormat.getChannels(), sourceFormat.getChannels() * 2, sourceFormat.getSampleRate(), false);
// 设置阿里语音识别的音频格式
AudioFormat pcmFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 16000, 16, 1, 2, 16000, false);
try (
// 先通过MP3转一次,使音频流能的格式完整
final AudioInputStream mp3AIS = AudioSystem.getAudioInputStream(mp3tFormat, sourceAIS);
// 转成阿里需要的流
final AudioInputStream pcmAIS = AudioSystem.getAudioInputStream(pcmFormat, mp3AIS)) {
// 根据路径生成wav文件
AudioSystem.write(pcmAIS, AudioFileFormat.Type.WAVE, new File(targetPath));
}
return true;
} catch (IOException e) {
System.out.println("文件转换异常:" + e.getMessage());
return false;
} catch (UnsupportedAudioFileException e) {
System.out.println("文件转换异常:" + e.getMessage());
return false;
}
}
%>
<%!
public static byte[] getBytes(String filepath){
byte[] buffer = null;
try{
File file = new File(filepath);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1000];
int n;
while((n=fis.read(b))!=-1){
bos.write(b,0,n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
}catch(Exception e){
e.printStackTrace();
}
return buffer;
}
%>