javaMP3转pcm 百度语音识别

YOLO_Y

不多说直接贴代码

import com.baidu.aip.speech.AipSpeech;
import javazoom.spi.mpeg.sampled.file.MpegAudioFileReader;
import org.json.JSONObject;
import java.util.*;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
public static final String APP_ID = "";
public static final String API_KEY = "";
public static final String SECRET_KEY = "";

public void test() throws Exception {
    AipSpeech client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);
    String path = "D:\\test2.mp3";
    String path2 = "D:\\test2.pcm";
    convertMP32Pcm(path, path2);
    JSONObject asrRes = client.asr(path2, "pcm", 16000, null);
    System.out.println(asrRes);
    System.out.println(asrRes.get("result"));
}
public boolean convertMP32Pcm(String mp3filepath, String pcmfilepath){
    try {
        //获取文件的音频流,pcm的格式
        AudioInputStream audioInputStream = getPcmAudioInputStream(mp3filepath);
        //将音频转化为  pcm的格式保存下来
        AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, new File(pcmfilepath));
        return true;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }
}
private static AudioInputStream getPcmAudioInputStream(String mp3filepath) {
    File mp3 = new File(mp3filepath);
    AudioInputStream audioInputStream = null;
    AudioFormat targetFormat = null;
    try {
        AudioInputStream in = null;
        MpegAudioFileReader mp = new MpegAudioFileReader();
        in = mp.getAudioInputStream(mp3);
        AudioFormat baseFormat = in.getFormat();
        targetFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16,
                baseFormat.getChannels(), baseFormat.getChannels()*2, baseFormat.getSampleRate(), false);
        audioInputStream = AudioSystem.getAudioInputStream(targetFormat, in);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return audioInputStream;
}

代码忘记借鉴了哪位大神的 不好意思 好像是综合了部分代码
下面的是依赖
<!-- https://mvnrepository.com/art... -->

<dependency>
    <groupId>com.googlecode.soundlibs</groupId>
    <artifactId>mp3spi</artifactId>
    <version>1.9.5.4</version>
</dependency>

http://mvnrepository.com/arti...
小程序录音MP3格式上传服务器 转化为pcm格式后通过百度语音识别结果

阅读 5.9k

专注写bug20年

74 声望
10 粉丝
0 条评论

专注写bug20年

74 声望
10 粉丝
宣传栏