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
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);
}