Search code examples
javascriptrestazurepostmanspeech-to-text

difference between api call and on postman


I was using Azure Speech rest api. And i tried it on post man with a .wav file and it successfully return the result. However, when i call api from my node.js code. It always return Unsupported Audio Format even though i give the same audio file. Can anyone tell me what's the difference of them? Or what did Postman do to make it work?

Below is how i call speech api by node.js.

'use strict';

const request = require('request');

const subscriptionKey = 'MYSUBSCRIPTIONKEY';

const uriBase = 'https://westus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US';

const options = {
    uri: uriBase,
    body: 'speech.wav',
    headers: {
        'Content-Type': 'application/json',
        'Ocp-Apim-Subscription-Key' : subscriptionKey,
        'Transfer-Encoding': 'chunked',
        'Expect': '100-continue',
        'Content-type':'audio/wav; codec=audio/pcm; samplerate=16000'
    }
};

request.post(options, (error, response, body) => {
  if (error) {
    console.log('Error: ', error);
    return;
  }
  let jsonResponse = JSON.stringify(JSON.parse(body), null, '  ');
  console.log('JSON Response\n');
  console.log(jsonResponse);
});

Solution

  • You can try this

    fs.readFile('/path/to/my/audiofile.wav', function (err, data) {
      if (err) throw err;
      var options = {
        host: 'https://westus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US',
        method: 'POST',
        headers: { 'Content-Type': 'audio/wav' }
      };
      var req = http.request(options, function(res) {
        // Handle a successful response here...
      });
      req.on('error', function(e) {
        // Handle an error response here...
      });
      // Write the audio data in the request body.
      req.write(data);
      req.end();
    });