React Native 使用返回示例的库的多个示例

yvfmudvl  于 2023-10-22  发布在  React
关注(0)|答案(1)|浏览(161)

我正在使用一个库(Voice),它返回它的一个示例。我做了下面的组件,成功地使用它
但是我需要以下组件在其他组件的多个示例。其中每个组件都有一个唯一的Voice示例
因此,我需要克隆导入的Voice对象,以便为以下组件的每个示例创建单独的/新的示例。
这个组件在任何时候都接收一个属性*unique_key*来标识它。我还将该密钥绑定到(克隆的)SpeechInstance以进行标识

import React, { Component } from 'react';
import { Text, View, Button} from 'react-native';
import Voice from '@react-native-voice/voice';

var all_speech_instances = [];

export default class VoiceRecorder extends Component {
    constructor(props) {
        super(props);            

        //like all_instances array Voice is global and its an instance returned by libraray
        // So i am cloning it to make specific/new for each instance of this component
        this.SpeechInstance = Object.assign(Object.create(Object.getPrototypeOf(Voice)), Voice);
        this.SpeechInstance.unique_key = props.unique_key;

        let obj_this = this;
        this.SpeechInstance.onSpeechError = function(e) { obj_this.onSpeechError(e) };
        this.SpeechInstance.onSpeechResults = function(e) { obj_this.onSpeechResults(e) };

        //Shown for proof of concept        
        all_speech_instances.push(this.SpeechInstance);
        if(all_speech_instances.length > 1){
            console.log('Instance 1 => unique_key='+all_speech_instances[0].unique_key); //shows 1
            console.log('Instance 2 => unique_key='+all_speech_instances[1].unique_key); //shows 2
        }
    }    

    _startRecognizing = async () => {
        await this.SpeechInstance.start();
    };
    _stopRecognizing = async () => {
        await this.SpeechInstance.stop();
    };

    onSpeechError(e) {
        // whenever error
        console.log('On speech error Key=' + this.SpeechInstance.unique_key);
        // always shows 2
    };
    onSpeechResults(e){        
        // whenever speech recognized
        console.log('On speech results Key=' + this.SpeechInstance.unique_key, e.value);
        //always shows 2
    };

    //Following tow functions are react-native specific
    componentWillUnmount() {
        this.SpeechInstance.removeAllListeners();
    }

    render() {
        let obj_this = this;
        return (
            <View style={{padding:10}}>
                <Text>unique_key: {this.SpeechInstance.unique_key}</Text>
                <View style={{padding: 5}}>
                    <Button onPress={()=>{ obj_this._startRecognizing()}} title='Start Listening' />
                </View>
                <View style={{padding: 5}}>
                    <Button onPress={()=>{ obj_this._stopRecognizing()}} title='Stop Listening' />
                </View>                                
            </View>
        );
    }
}

用法我使用上面的组件非常简单

import React from 'react';
import {View} from 'react-native';
import SpeechComponent from '../voice/SpeechComponent';

export default class VoiceTestScreen extends React.Component {
    render(){
        return(
            <View>
                <SpeechComponent unique_key='1'/>
                <SpeechComponent unique_key='2'/>
            </View>
        );
    }
}

经过非常小心的封装,将SpeechInstance隐藏在组件示例中,使其不能被全局共享,我仍然总是使用组件的第一个示例或第二个示例开始识别(在按钮单击时开始),结果=> console On speech results Key=2

a64a0gku

a64a0gku1#

**这个解释需要改进:**我的问题不正确,@begi在评论中做了更正,并且在阅读他指出的Api文档后,我认为这是API特定的问题,因为单个麦克风不能被多个示例分别监听。

所以我尝试了另一种方法,得到了解决方案。

import React from 'react';
import {View} from 'react-native';
import SpeechComponent from '../voice/SpeechComponent';

export default class TestMultiVoice extends React.Component {
    render(){
        return(
            <View>
                <SpeechComponent unique_key='1'/>
                <SpeechComponent unique_key='2'/>
            </View>
        );
    }
}

我所欺骗的是在Voice.start之前克隆单个静态API示例Voice,然后在onError和onResult上完全销毁它。

import React, { Component } from 'react';
import { Text, View, Button} from 'react-native';
import Voice from '@react-native-voice/voice';

export default class SpeechComponent extends Component {
constructor(props) {
    super(props);
    this.state = {
        obtainedText: 'Recognized text will be displayed here'
    }
}    

_startRecognizing = async () => {
    let obj_this = this;
    this.SpeechInstance = Object.assign(Object.create(Object.getPrototypeOf(Voice)), Voice);
    this.SpeechInstance.onSpeechError = (e) => obj_this.onSpeechError(e);
    this.SpeechInstance.onSpeechResults = (e) => this.onSpeechResults(e);
    await this.SpeechInstance.start();
};
_stopRecognizing = async () => {
    await Voice.stop();
};

onSpeechError(e) {
    // whenever error
    console.log('On speech error Key=' + Voice.unique_key);
    this.onSpeechComplete();
    this.setState({obtainedText: e.error.message});
    // always shows 2
};
onSpeechResults(e){        
    // whenever speech recognized
    console.log('On speech results Key=' + Voice.unique_key, e.value);
    this.onSpeechComplete();
    this.setState({obtainedText: e.value[0]})
    //always shows 2
};

onSpeechComplete(){            
    this.SpeechInstance.destroy().then(this.SpeechInstance.removeAllListeners);
}

render() {
    let obj_this = this;
    return (
        <View style={{padding:10}}>
            <Text>unique_key: {Voice.unique_key}</Text>
            <View style={{padding: 5}}>
                <Button onPress={()=>{ obj_this._startRecognizing()}} title='Start Listening' />
            </View>
            <View style={{padding: 5}}>
                <Button onPress={()=>{ obj_this._stopRecognizing()}} title='Stop Listening' />
            </View>
            <View>
                <Text>Obtained Tex: {this.state.obtainedText}</Text>
            </View>
        </View>
    );
}

}

相关问题