微软语音 API 错误请求

问题描述 投票:0回答:1

任何人都可以检查我的代码是否有错误:这是为微软语音 API 传递字节,但是我收到了 400 bad request 错误。 wav 文件格式是正确的,因为我使用了微软的示例。任何帮助将不胜感激!

public void speechToText(){
    String Key = "mysubscriptionkey";
    try {
        File file = new File("filepath", "filename.wav");
        URL url = new URL("https://westus.stt.speech.microsoft.com/speech/recognition/interactive/cognitiveservices/v1?langauge=en-US&format=simple");

        HttpURLConnection con =(HttpURLConnection)url.openConnection();
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        con.setRequestProperty("Accept", "application/json");
        con.addRequestProperty("Content-type", "audio/wav; codec=\"audio/pcm\"; samplerate=16000"); 
        con.addRequestProperty("Ocp-Apim-Subscription-Key", Key);

        byte[] bytes = ReadFully(file);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.write(bytes);

        Scanner scanner = new Scanner(con.getInputStream()); 
        String responseBody = scanner.useDelimiter("\\A").next();
        System.out.println(responseBody);
    }
    catch (Exception e) 
            {
                e.printStackTrace();
            }

--这个是读音频的

public byte[] ReadFully(File file){
ByteArrayOutputStream out = new ByteArrayOutputStream();
try{
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
    byte[] buffer = new byte[1024];
        int bytesRead;
        OutputStream outputstream ;
        while ((bytesRead = in.read(buffer)) != -1){
        out.write(buffer, 0, bytesRead);
    }
    }
    catch (Exception e){
        e.printStackTrace();
    }
   return out.toByteArray();
}
web-services speech-to-text bad-request web-api-testing
1个回答
0
投票

我遇到了同样的问题,最后将使用curl 的成功终端请求与我自己的代码进行了比较。由于某种原因,Microsoft 认知语音 API 不喜欢缺少“User-Agent”标头,我的 400 Bad 请求问题只需在请求中添加一个假的 User-Agent 标头即可解决。

© www.soinside.com 2019 - 2024. All rights reserved.