uniquejava / blog

My notes regarding the vibrating frontend :boom and the plain old java :rofl.
Creative Commons Zero v1.0 Universal
11 stars 5 forks source link

flutter stt #285

Open uniquejava opened 4 years ago

uniquejava commented 4 years ago

插件

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  speech_to_text: ^1.1.0
uniquejava commented 4 years ago

cyper实战

import 'package:flutter/material.dart';
import 'package:speech_to_text/speech_recognition_error.dart';
import 'package:speech_to_text/speech_recognition_result.dart';
import 'package:speech_to_text/speech_to_text.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _available = false;
  bool _listening = false;

  String _currentLocaleId = "";
  List<LocaleName> _localeNames = [];
  final SpeechToText speech = SpeechToText();

  Future<void> initSpeechState() async {
    bool available = await speech.initialize(
        onError: errorListener, onStatus: statusListener);
    if (available) {
      _localeNames = await speech.locales();

      print(_localeNames);

      var systemLocale = await speech.systemLocale();
      _currentLocaleId = systemLocale.localeId;

      print(_currentLocaleId);
    } else {
      print("The user has denied the use of speech recognition.");
    }
    if (!mounted) return;

    setState(() {
      _available = available;
    });
  }

  void errorListener(SpeechRecognitionError error) {
    print("${error.errorMsg} - ${error.permanent}");
  }

  void statusListener(String status) {
    setState(() {
      _listening = status == 'listening';
    });
  }

  void startListening() {
    speech.listen(
        onResult: resultListener,
        listenFor: Duration(seconds: 10),
        localeId: _currentLocaleId,
        onSoundLevelChange: soundLevelListener,
        cancelOnError: true,
        partialResults: true);
  }

  void resultListener(SpeechRecognitionResult result) {
    var lastWords = "${result.recognizedWords} - ${result.finalResult}";
    print('last words: $lastWords');
  }

  void soundLevelListener(double level) {
    print('level: $level');
  }

  void stopListening() {
    speech.stop();
  }

  void cancelListening() {
    speech.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            FlatButton(
              child: Text('Initialize'),
              onPressed: _available ? null : initSpeechState,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                FlatButton(
                  child: Text('Start'),
                  onPressed: !_available || _listening ? null : startListening,
                ),
                FlatButton(
                  child: Text('Stop'),
                  onPressed: _listening ? stopListening : null,
                ),
                FlatButton(
                  child: Text('Cancel'),
                  onPressed: _listening ? cancelListening : null,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}