flutter开发----播放文本功能

前言

现在许多的景区都采用了语音介绍了,就想用flutter来实现这个功能。今天我就找个一个插件来使用这个---------tts

准备工具

这套课程是采用Android Studio进行开发的。当前在此之前请准备好Flutter开发环境,我这里就不进行讲解了。

展示结果
在这里插入图片描述

导入插件

首先导入我们的插件

tts: ^1.0.2

小实例开发流程

ttr工具类

import 'package:tts/tts.dart';

import 'dart:async';
import 'dart:io';

/// Singleton tool class for tts

/// Use TtsHelper step:
///
/// Method : #isLanguageAvailable judge language, here language is _languageMap's values like "en-US",instead of the type of 'en' etc..
///
/// Method : #getTtsLanguage  help you convert "en" to "en-US".
///
/// Method : #setLanguage help you set Language , but "en-US" is default value
///
/// use example:
/// TtsHelper.instance.speak("speech content");
/// or
/// TtsHelper.instance.setLanguageAndSpeak("speech content", "en-US");
/// ...
class TtsHelper {

  // Locale to tss language map
  static final Map<String, String> _languageMap = {
    'en': "en-US",
    'zh': "zh-CN",
    "ar": "ar-SA",
    "cs": "cs-CZ",
    "da": "da-DK",
    "de": "de-DE",
    "el": "el-GR",
    "es": "es-ES",
    "fi": "fi-FI",
    "fr": "fr-CA",
    "he": "he-IL",
    "hi": "hi-IN",
    "hu": "hu-HU",
    "id": "id-ID",
    "it": "it-IT",
    "ja": "ja-JP",
    "ko": "ko-KR",
    "nl": "nl-BE",
    "no": "no-NO",
    "pl": "pl-PL",
    "pt": "pt-BR",
    "ro": "ro-RO",
    "ru": "ru-RU",
    "sk": "sk-SK",
    "sv": "sv-SE",
    "th": "th-TH",
    "tr": "tr-TR",
    'en-US': "en-US",
    'zh-CN': "zh-CN",
    "ar-SA": "ar-SA",
    "cs-CZ": "cs-CZ",
    "da-DK": "da-DK",
    "de-DE": "de-DE",
    "el-GR": "el-GR",
    "es-ES": "es-ES",
    "fi-FI": "fi-FI",
    "fr-CA": "fr-CA",
    "he-IL": "he-IL",
    "hi-IN": "hi-IN",
    "hu-HU": "hu-HU",
    "id-ID": "id-ID",
    "it-IT": "it-IT",
    "ja-JP": "ja-JP",
    "ko-KR": "ko-KR",
    "nl-BE": "nl-BE",
    "no-NO": "no-NO",
    "pl-PL": "pl-PL",
    "pt-BR": "pt-BR",
    "ro-RO": "ro-RO",
    "ru-RU": "ru-RU",
    "sk-SK": "sk-SK",
    "sv-SE": "sv-SE",
    "th-TH": "th-TH",
    "tr-TR": "tr-TR",
  };

  static final String _defaultL = "en-US";
  List<String> _languages;
  static TtsHelper _instance;
  static TtsHelper get instance => _getInstance();

  factory TtsHelper() =>_getInstance();

  static TtsHelper _getInstance() {
    if (_instance == null) {
      _instance = new TtsHelper._internal();
    }
    return _instance;
  }

  TtsHelper._internal() {
    // Initialize
    _initPlatformState();
  }

  _initPlatformState() async {
    _languages = await Tts.getAvailableLanguages();

    // If getAvailableLanguages is null, add "en-US" to _languages.
    if (_languages == null) {
      _languages = [_defaultL];
    }
    // Default set en-US language
    _setLanguage(_defaultL);
  }

  String _getTtsLanguage(String localeStr) {
    if(localeStr == null || localeStr.isEmpty ||
        !_languageMap.containsKey(localeStr)) {
      return _defaultL;
    }
    return _languageMap[localeStr];
  }

  // Return whether the result if set language is successful
  Future<bool> _setLanguage (String lang) async {
    String language = _getTtsLanguage(lang);
    if (language == null || language.isEmpty) {
      language = _defaultL;
    }
    if(Platform.isIOS && !_languages.contains(language)) {
      return false;
    }
    final bool isSet = await Tts.setLanguage(language);
    return isSet;
  }

  // Returns whether the supported language is supported
  Future<bool> _isLanguageAvailable (String language) async {
    final bool isSupport = await Tts.isLanguageAvailable(language);
    return isSupport;
  }

  void speak (String text) async {
    if (text == null || text.isEmpty) { return;}
    Tts.speak(text);
  }

  void setLanguageAndSpeak(String text, String language) async {
    String ttsL = _getTtsLanguage(language);
    var setResult = await _setLanguage(ttsL);
    if(setResult != null) {
      var available = await _isLanguageAvailable(ttsL);
      if(available != null) {
        speak(text);
      }
    }
  }

}

景区语音界面

import 'package:yuyin/ttsHelper.dart';
import 'package:flutter/material.dart';

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

  final String title;

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

class _VoiceSetPageState extends State<VoiceSetPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(

        backgroundColor: Colors.blue,
        title: Text('绍兴景区导游词'),
        elevation: 5.0, // shadow the bottom of AppBar
      ),
      body: Center(
        child: ListView(
          children: <Widget>[
            ListTile(
              title: Text(
                '绍兴龙华寺导游词',
                style: TextStyle(fontWeight: FontWeight.w500, fontSize: 20.0),
              ),
              onTap: () {
                TtsHelper.instance.setLanguageAndSpeak("龙华寺初建于南朝宋元嘉二十四年(447年),是当时的吏部尚书江夷建造。夷父江彪,东晋永和中任会稽内史,龙华寺之地原为其宅居。夷六世孙江揔,为南朝陈尚书令,曾于梁太清(547——549)末,避难于会稽龙华寺内。", "zh");
              },
            ),
            ListTile(
              title: Text(
                '绍兴东湖导游词',
                style: TextStyle(fontWeight: FontWeight.w500, fontSize: 20.0),
              ),
              onTap: () {
                TtsHelper.instance.setLanguageAndSpeak("绍兴东湖在绍兴古城东约六公里处,以崖壁、岩洞、石桥、湖面巧妙结合,成为著名园林,是浙江省的三大名湖之一。东湖虽小,但因它的奇石、奇洞所构成的奇景使东湖成为旅游业界人士公认的罕见的\"湖中之奇\"。日本旅游机构交通公社,曾在同时游历过杭州西湖与绍兴东湖的日本游客中作过问卷调查,对东湖的印象超过西湖,可见对东湖的赞誉并非绍兴人的自我感觉。", "zh");
              },
            ),
             ListTile(
              title: Text(
                '绍兴大禹陵导游词',
                style: TextStyle(fontWeight: FontWeight.w500, fontSize: 20.0),
              ),
              onTap: () {
                TtsHelper.instance.setLanguageAndSpeak("大禹陵位于绍兴东南的会稽山脚下,会稽山风景区内。相传八年治水、三过家门而不入的大禹就葬在这里。虽然目前景区新开辟了百鸟苑景点,一旁还有香火甚旺的香炉峰,但会稽山景区的精华依然是以大禹为主题的古迹——禹陵、禹祠和禹庙。", "zh");
              },
            ),
            Divider(
              height: 1,
            )
          ],
        ),
      ),
    );
  }
}


主页面跳转子页面

import 'package:flutter/material.dart';
import './vice.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: '播放文本'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {

  void _incrementCounter() {
    Navigator.push(context, MaterialPageRoute(builder: (context) => VoiceSetPage(title: "Setting")));
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '景区简介语音播报',
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: '跳转',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}


重点内容

	ListTile(
              title: Text(
                '绍兴大禹陵导游词',
                style: TextStyle(fontWeight: FontWeight.w500, fontSize: 20.0),
              ),
              onTap: () {
                TtsHelper.instance.setLanguageAndSpeak("大禹陵位于绍兴东南的会稽山脚下,会稽山风景区内。相传八年治水、三过家门而不入的大禹就葬在这里。虽然目前景区新开辟了百鸟苑景点,一旁还有香火甚旺的香炉峰,但会稽山景区的精华依然是以大禹为主题的古迹——禹陵、禹祠和禹庙。", "zh");
              },
            ),

完整的项目已经传到我的github供大家学习,编写不易,希望大家给一个赞.

发布了49 篇原创文章 · 获赞 35 · 访问量 3万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览