如何使onSpeechVolumeChanged中的平均值React Native

wmomyfyw  于 2022-12-04  发布在  React
关注(0)|答案(2)|浏览(100)

我在react native中有一个语音到文本的项目,现在的问题是语音Vlume,如何从这个函数中获得平均值?

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

控制台中的日志为:

{"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}

这里有一个编码器,可以把语音转换成文本。这里有一个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);
  };

这里需要一个NuN

v2g6jxz6

v2g6jxz61#

const [voiceData, setVoiceData] = useState([]);
useEffect(() => {
    Voice.onSpeechError = onSpeechError;
    Voice.onSpeechResults = onSpeechResults;
    Voice.onSpeechVolumeChanged = onSpeechVolumeChanged;
    // added this line ->
    Voice.onSpeechStart = onSpeechStart;
    return () => {
        Voice.destroy().then(Voice.removeAllListeners);
    }
}, []);
// added thit lines ->
const onSpeechStart = (e) => {
    // flush the data array
    voiceData.splice(0, voiceData.length);
    // if not works try this ->
    setVoiceData([]);
}
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);
    voiceData.push(e.value);
}
qyswt5oh

qyswt5oh2#

是否要对一定数量的数据求平均值?例如,可以在数组中保留10个数据,然后将平均值提供给setPitch函数

相关问题