Home > Software design >  How to make average value in onSpeechVolumeChanged react native
How to make average value in onSpeechVolumeChanged react native

Time:12-02

I have i project with speech-to-text in react native, and now the problem in with speech Vloume, how to make average value from this function?

 const onSpeechVolumeChanged = (e) => {
    console.log(e);
    setPitch(e.value);
  };

And the log in the console is:

{"value": -2}
 LOG  {"value": -0.440000057220459}
 LOG  {"value": 0.7599999904632568}
 LOG  {"value": 1.3600001335144043}
 LOG  {"value": -0.440000057220459}
 LOG  {"value": -1.7599999904632568}
 LOG  {"value": -2}
 LOG  {"value": 0.2799999713897705}
 LOG  {"value": 1}
 LOG  {"value": 2.440000057220459}
 LOG  {"value": 2.8000001907348633}
 LOG  {"value": 5.920000076293945}

There is a codem with makes speech to text. And y take here a NaN

  let [started, setStarted] = useState(false);
  let [results, setResults] = useState([]);
  const [voiceData, setVoiceData] = useState([])
}
  useEffect(() => {
    Voice.onSpeechError = onSpeechError;
    Voice.onSpeechResults = onSpeechResults;
    Voice.onSpeechVolumeChanged = onSpeechVolumeChanged;

    return () => {
      Voice.destroy().then(Voice.removeAllListeners);
      
    }
  }, []);

  const startSpeechToText = async () => {
    await Voice.start("ru");
    setStarted(true);
  };

  const onSpeechVolumeChanged = (e) => {
    setVoiceData({...voiceData, volume: e.value});
  };

  const stopSpeechToText = async () => {
    await Voice.stop();
    setStarted(false);
  };

  const onSpeechResults = (result) => {
    var allValue = result.value
    var theBestOption = allValue[Object.keys(allValue).pop()]
    setResults(theBestOption)
    console.log(theBestOption)
    let sum = 0;
    let count = 0;
    for (let i = 0; i < voiceData.length; i  ) {
        sum  = voiceData[i];
        count  ;
    }
    let average = sum / count;
    console.log(average)
  };

  const onSpeechError = (error) => {
    console.log(error);
  };

Here takes an NuN

CodePudding user response:

const [voiceData, setVoiceData] = useState([]);
useEffect(() => {
    Voice.onSpeechError = onSpeechError;
    Voice.onSpeechResults = onSpeechResults;
    Voice.onSpeechVolumeChanged = onSpeechVolumeChanged;

    return () => {
        Voice.destroy().then(Voice.removeAllListeners);
    }
}, []);

const onSpeechError = (e) => {
    console.log('onSpeechError: ', e);
}
const onSpeechResults = (e) => {
    let sum = 0;
    let count = 0;
    for (let i = 0; i < voiceData.length; i  ) {
        sum  = voiceData[i];
        count  ;
    }
    let average = sum / count;
    console.log(average)
}
const onSpeechVolumeChanged = (e) => {
    console.log('onSpeechVolumeChanged: ', e);
    setVoiceData([...voiceData, e.value]);
}

CodePudding user response:

Do you want to average a certain amount of data? For example, you can keep 10 data in an array and give the average to setPitch function

  • Related