无声失败,伴有speech_to_text Flutter

ulmd4ohb  于 2023-03-13  发布在  Flutter
关注(0)|答案(1)|浏览(240)

我正在尝试将语音转文本功能集成到flutter应用程序中。但是,我的尝试都不起作用。下面是我的dart代码:

import 'package:client/main.dart';
import 'package:flutter/material.dart';

import 'package:client/language/nlp.dart';
import 'package:speech_to_text/speech_recognition_result.dart';
import 'package:speech_to_text/speech_to_text.dart';

class Home extends StatefulWidget{
  const Home({super.key});

  @override
  State<Home> createState() => HomeState();
}

class HomeState extends State<Home>{
  @override
  BuildContext context = navigatorKey.currentState!.context;

  SpeechToText _speechToText = SpeechToText();
  bool _speechEnabled = false;
  String _lastWords = "";
  Language nlp = Language();

  @override
  void initState(){
    super.initState();
    _initSpeech();
  }

  void _initSpeech() async {
    _speechEnabled = await _speechToText.initialize();
    setState(() {});
  }

  void _startListening() async {
    await _speechToText.listen(onResult: _onSpeechResult);
    setState(() {});
  }

  void _stopListening() async {
    await _speechToText.stop();
    setState(() {});
  }

  void _onSpeechResult(SpeechRecognitionResult result){
    setState(() {
      _lastWords = result.recognizedWords;
      print(result.recognizedWords);
      nlp.parseInput(result.recognizedWords);
    });
  }

  @override
  Widget build(BuildContext context){
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              padding: EdgeInsets.all(16),
              child: const Text(
                "Recognised words:",
                style: TextStyle(fontSize: 20.0),
              ),
            ),
            Expanded(
              child: Container(
                padding: EdgeInsets.all(16),
                child: Text(
                  _speechToText.isListening
                      ? '$_lastWords'
                      : _speechEnabled
                        ? 'Tap the microphone to start listening...'
                        : "Speech not available",                ),
              ),
            )
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _speechToText.isNotListening ? _startListening : _stopListening,
        child: Icon(_speechToText.isNotListening ? Icons.mic_off : Icons.mic),
      ),
    );
  }
}

有人知道如何让它工作吗?没有显示错误信息,但是语音输入没有被发送到nlp.parseInput()函数,也没有被打印出来。我试着在谷歌上搜索它,但没有找到任何解决方案。

83qze16e

83qze16e1#

通过确保在我的系统设置中选择了正确的麦克风,问题得到了解决。

相关问题