Azure speech to text in react-native wav file pass issue

422 Views Asked by At

I want use Azure's STT REST API for my react-native app with recorded audio. But I've try to search how to pass the wav file but always response "No audio data received" or other error response.

I'm very sure the subscribe key is working cause when I use get token it responses 200. And the wav file is not the problem,either.Cause when I download the file to my computer then upload it in Azure STT's homepage,it responses the correct answer. The last,I've tried to figure out how to pass it in right form,but every things are for website. Here's my code `

  const file = new ReactNativeFile({
    uri:
      `file://${audioFile}`,
    type: 'audio/wav',
    name: 'ABCS160101e1a011b160a3e169d7b0.wav',
  });
  let form = new formData();
  const headers = {
    'Ocp-Apim-Subscription-Key': 'MyKey',
    'Content-type': 'audio/wav; codecs=audio/pcm;samplerate=16000',
    Accept: 'application/json',
  };

  const url = `https://eastasia.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US`;

  await form.append('audio', file);

  console.log('before');
  let response = await axios.post(url, form, {
    headers: headers,
  });
  console.log('after');
  console.log('result', JSON.stringify(response));
} catch (err) {
  getlog.cw('err23', err);
  return err;
}

};`

and Here's My recording function in another place,it's working for play.

import AudioRecord from 'react-native-audio-record';
const options = {
  sampleRate: 16000, // default 44100
  bitsPerSample: 16, // 8 or 16, default 16,
  wavFile: "ABCS160101e1a011b160a3e169d7b0.wav"
};
     const toggleRecord = async () => {
    if (isRecording) {
      const audioFile = await AudioRecord.stop();
      setIsRecording(false);
      // reloadRecorder();
    } else {
      setIsRecording(true);
      AudioRecord.init(options);
      AudioRecord.start();
    }

};

1

There are 1 best solutions below

0
On

Firstly, write

let form = new FormData();

Instead of

let form = new formData();

Secondly, I suppose you audioFile looks like this - file://.... So you dont have to write like this uri: file://${audioFile} ..You can simply write

uri:audioFile

SO final implementation would be

let form = new FormData();

    form.append('audio', {
      uri: audioFile,
      type: 'audio/wav',
      name: 'ABCS160101e1a011b160a3e169d7b0.wav',
    });

    const headers = {
      'Ocp-Apim-Subscription-Key': 'MyKey',
      'Content-type': 'audio/wav; codecs=audio/pcm;samplerate=16000',
      Accept: 'application/json',
    };

    const url = `https://eastasia.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US`;

    console.log('before');
    let response = await axios.post(url, form, {
      headers: headers,
    });
    console.log('after');
    console.log('result', JSON.stringify(response));