react-native-voice2text
Version:
React Native module for Android that converts speech to text using native speech recognition
70 lines (69 loc) • 2.37 kB
JavaScript
;
import { NativeModules, NativeEventEmitter, PermissionsAndroid, Platform } from 'react-native';
const {
Voice2Text
} = NativeModules;
const eventEmitter = new NativeEventEmitter(Voice2Text);
const Voice2TextModule = {
async checkPermissions() {
if (Platform.OS === 'android') {
return PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.RECORD_AUDIO);
}
// iOS permissions handled by native side or not required here
return true;
},
async requestPermissions() {
if (Platform.OS === 'android') {
const result = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.RECORD_AUDIO);
return result === PermissionsAndroid.RESULTS.GRANTED;
}
return true;
},
async startListening(languageCode) {
const hasPermission = await this.checkPermissions();
if (!hasPermission) {
const granted = await this.requestPermissions();
if (!granted) throw new Error('Permission not granted');
}
return Voice2Text.startListening(languageCode ?? null);
},
stopListening() {
return Voice2Text.stopListening();
},
cancelListening() {
return Voice2Text.cancelListening();
},
destroy() {
return Voice2Text.destroy();
},
onResults(callback) {
const subscription = eventEmitter.addListener('onSpeechResults', callback);
return () => subscription.remove();
},
onPartialResults(callback) {
const subscription = eventEmitter.addListener('onSpeechPartialResults', callback);
return () => subscription.remove();
},
onError(callback) {
const subscription = eventEmitter.addListener('onSpeechError', callback);
return () => subscription.remove();
},
onSpeechStart(callback) {
const subscription = eventEmitter.addListener('onSpeechStart', callback);
return () => subscription.remove();
},
onSpeechBegin(callback) {
const subscription = eventEmitter.addListener('onSpeechBegin', callback);
return () => subscription.remove();
},
onSpeechEnd(callback) {
const subscription = eventEmitter.addListener('onSpeechEnd', callback);
return () => subscription.remove();
},
onVolumeChanged(callback) {
const subscription = eventEmitter.addListener('onSpeechVolumeChanged', callback);
return () => subscription.remove();
}
};
export default Voice2TextModule;
//# sourceMappingURL=index.js.map