当前位置: 首页 > news >正文

Qt文档阅读笔记-Hello Speak Example

官方的这个例子比较有意思,在此记录下,方便以后查阅。

Hello Speak Example

这个例子主要是使用QTextToSpeech类将用户自定义输入的文本转换为口语,包括高低音、声音大小、读速。并且能够选择语言和声音。

包含的文件如下:

 

本篇博文,主要记录下如何使用QTextToSpeech将文字转换为口语。

QTextToSpeech Class

这里先来看下这个类,使用他需要在pro文件添加texttospeech。关于这个类的描述如下:

QTextToSpeech类提供了text-to-speech的引擎,这个引擎使用及其方便。

使用say(),就能将文字转换为口语,并且他能通过setLocale()指定语言,使用setVoice()选择声音。这里有点要注意这些语言和声音依赖于本地机器是否支持。

下面是关于QTextToSpeech::State

constantvaluedescription
QTextToSpeech::Ready0文本输入完后,准备将输入的文本转换为口语。
QTextToSpeech::Speaking1文本正在转换为口语。
QTextToSpeech::Paused2暂停,调用resume()进行恢复。
QTextToSpeech::BackendError3转换口语后端发生错误时

解析

下面主要是来看下,这个例子,是如何将文本转换为口语的。

关键.h文件:

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QtWidgets/qmainwindow.h>

#include "ui_mainwindow.h"

#include <QTextToSpeech>

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow(QWidget *parent = 0);

public slots:
    void speak();
    void stop();

    void setRate(int);
    void setPitch(int);
    void setVolume(int volume);

    void stateChanged(QTextToSpeech::State state);
    void engineSelected(int index);
    void languageSelected(int language);
    void voiceSelected(int index);

    void localeChanged(const QLocale &locale);

private:
    Ui::MainWindow ui;
    QTextToSpeech *m_speech;
    QVector<QVoice> m_voices;
};

#endif

关键.cpp文件

mainwindow.cpp

#include "mainwindow.h"
#include <QLoggingCategory>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
    m_speech(0)
{
    ui.setupUi(this);
    //QLoggingCategory::setFilterRules(QStringLiteral("qt.speech.tts=true \n qt.speech.tts.*=true"));

    // Populate engine selection list
    ui.engine->addItem("Default", QString("default"));
    foreach (QString engine, QTextToSpeech::availableEngines())
        ui.engine->addItem(engine, engine);
    ui.engine->setCurrentIndex(0);
    engineSelected(0);

    connect(ui.speakButton, &QPushButton::clicked, this, &MainWindow::speak);
    connect(ui.pitch, &QSlider::valueChanged, this, &MainWindow::setPitch);
    connect(ui.rate, &QSlider::valueChanged, this, &MainWindow::setRate);
    connect(ui.volume, &QSlider::valueChanged, this, &MainWindow::setVolume);
    connect(ui.engine, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &MainWindow::engineSelected);
}

void MainWindow::speak()
{
    m_speech->say(ui.plainTextEdit->toPlainText());
}
void MainWindow::stop()
{
    m_speech->stop();
}

void MainWindow::setRate(int rate)
{
    m_speech->setRate(rate / 10.0);
}

void MainWindow::setPitch(int pitch)
{
    m_speech->setPitch(pitch / 10.0);
}

void MainWindow::setVolume(int volume)
{
    m_speech->setVolume(volume / 100.0);
}

void MainWindow::stateChanged(QTextToSpeech::State state)
{
    if (state == QTextToSpeech::Speaking) {
        ui.statusbar->showMessage("Speech started...");
    } else if (state == QTextToSpeech::Ready)
        ui.statusbar->showMessage("Speech stopped...", 2000);
    else if (state == QTextToSpeech::Paused)
        ui.statusbar->showMessage("Speech paused...");
    else
        ui.statusbar->showMessage("Speech error!");

    ui.pauseButton->setEnabled(state == QTextToSpeech::Speaking);
    ui.resumeButton->setEnabled(state == QTextToSpeech::Paused);
    ui.stopButton->setEnabled(state == QTextToSpeech::Speaking || state == QTextToSpeech::Paused);
}

void MainWindow::engineSelected(int index)
{
    QString engineName = ui.engine->itemData(index).toString();
    delete m_speech;
    if (engineName == "default")
        m_speech = new QTextToSpeech(this);
    else
        m_speech = new QTextToSpeech(engineName, this);
    disconnect(ui.language, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &MainWindow::languageSelected);
    ui.language->clear();
    // Populate the languages combobox before connecting its signal.
    QVector<QLocale> locales = m_speech->availableLocales();
    QLocale current = m_speech->locale();
    foreach (const QLocale &locale, locales) {
        QString name(QString("%1 (%2)")
                     .arg(QLocale::languageToString(locale.language()))
                     .arg(QLocale::countryToString(locale.country())));
        QVariant localeVariant(locale);
        ui.language->addItem(name, localeVariant);
        if (locale.name() == current.name())
            current = locale;
    }
    setRate(ui.rate->value());
    setPitch(ui.pitch->value());
    setVolume(ui.volume->value());
    connect(ui.stopButton, &QPushButton::clicked, m_speech, &QTextToSpeech::stop);
    connect(ui.pauseButton, &QPushButton::clicked, m_speech, &QTextToSpeech::pause);
    connect(ui.resumeButton, &QPushButton::clicked, m_speech, &QTextToSpeech::resume);

    connect(m_speech, &QTextToSpeech::stateChanged, this, &MainWindow::stateChanged);
    connect(m_speech, &QTextToSpeech::localeChanged, this, &MainWindow::localeChanged);

    connect(ui.language, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &MainWindow::languageSelected);
    localeChanged(current);
}

void MainWindow::languageSelected(int language)
{
    QLocale locale = ui.language->itemData(language).toLocale();
    m_speech->setLocale(locale);
}

void MainWindow::voiceSelected(int index)
{
    m_speech->setVoice(m_voices.at(index));
}

void MainWindow::localeChanged(const QLocale &locale)
{
    QVariant localeVariant(locale);
    ui.language->setCurrentIndex(ui.language->findData(localeVariant));

    disconnect(ui.voice, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &MainWindow::voiceSelected);
    ui.voice->clear();

    m_voices = m_speech->availableVoices();
    QVoice currentVoice = m_speech->voice();
    foreach (const QVoice &voice, m_voices) {
        ui.voice->addItem(QString("%1 - %2 - %3").arg(voice.name())
                          .arg(QVoice::genderName(voice.gender()))
                          .arg(QVoice::ageName(voice.age())));
        if (voice.name() == currentVoice.name())
            ui.voice->setCurrentIndex(ui.voice->count() - 1);
    }
    connect(ui.voice, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &MainWindow::voiceSelected);
}

下面来跟一下这个m_speech是如何用的。

在.cpp中可以看到:

将engineName传入了QTextToSpeech的构造函数,而engineName的值来自于

QTextToSpeech::availableEngines()。

这里来看下,他是如何选择语言和音频的,

connect(ui.language, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &MainWindow::languageSelected);
connect(ui.voice, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &MainWindow::voiceSelected);

对应的槽函数分别为:

void MainWindow::languageSelected(int language)
{
    QLocale locale = ui.language->itemData(language).toLocale();
    m_speech->setLocale(locale);
}

void MainWindow::voiceSelected(int index)
{
    m_speech->setVoice(m_voices.at(index));
}

从中可以看到,这里封装好的,应用层调用的确是简单太多。

下面看下,他是如何播放、暂停、续播:

connect(ui.stopButton, &QPushButton::clicked, m_speech, &QTextToSpeech::stop);
connect(ui.pauseButton, &QPushButton::clicked, m_speech, &QTextToSpeech::pause);
connect(ui.resumeButton, &QPushButton::clicked, m_speech, &QTextToSpeech::resume);

关于设置音调,读速的相关代码如下:

void MainWindow::setRate(int rate)
{
    m_speech->setRate(rate / 10.0);
}

void MainWindow::setPitch(int pitch)
{
    m_speech->setPitch(pitch / 10.0);
}

void MainWindow::setVolume(int volume)
{
    m_speech->setVolume(volume / 100.0);
}

相关文章:

  • 【Golang开发面经】知乎(两轮技术面)
  • 1024程序员节:从关注自身健康开始
  • 负载均衡式在线OJ
  • SQL注入天书笔记(1)布尔盲注
  • 【2022集创赛】安谋科技杯一等奖作品:Cortex-M0智能娱乐收音机
  • python3-python中的多任务处理利器-协程的使用(一),asyncio模块的使用
  • vue06安装vue-cli+使用vue-cli搭建项目+什么是*.vue文件+开发示例+必问面试知识点
  • chrome盗取用户身份
  • 队列(Queue)的详解
  • 快速发布windows上的web项目【免费内网穿透】
  • 【C++笔试强训】第十一天
  • [Linux打怪升级之路]-vim编辑器(看就能马上操作噢)
  • 睿智的目标检测61——Keras搭建YoloV7目标检测平台
  • DM8: 达梦数据库生成100以内2位数加减法
  • 《数据结构》(六)八大排序(上)
  • 【干货分享】SpringCloud微服务架构分布式组件如何共享session对象
  • 2019.2.20 c++ 知识梳理
  • canvas实际项目操作,包含:线条,圆形,扇形,图片绘制,图片圆角遮罩,矩形,弧形文字...
  • CSS3 聊天气泡框以及 inherit、currentColor 关键字
  • Django 博客开发教程 16 - 统计文章阅读量
  • Java 11 发布计划来了,已确定 3个 新特性!!
  • NSTimer学习笔记
  • vue总结
  • Yeoman_Bower_Grunt
  • 基于web的全景—— Pannellum小试
  • 基于阿里云移动推送的移动应用推送模式最佳实践
  • 力扣(LeetCode)357
  • 三栏布局总结
  • 什么软件可以剪辑音乐?
  • 使用docker-compose进行多节点部署
  • 使用阿里云发布分布式网站,开发时候应该注意什么?
  • 移动端 h5开发相关内容总结(三)
  • 容器镜像
  • # MySQL server 层和存储引擎层是怎么交互数据的?
  • #DBA杂记1
  • $.type 怎么精确判断对象类型的 --(源码学习2)
  • (14)Hive调优——合并小文件
  • (14)目标检测_SSD训练代码基于pytorch搭建代码
  • (2015)JS ES6 必知的十个 特性
  • (html5)在移动端input输入搜索项后 输入法下面为什么不想百度那样出现前往? 而我的出现的是换行...
  • (Matlab)基于蝙蝠算法实现电力系统经济调度
  • (附表设计)不是我吹!超级全面的权限系统设计方案面世了
  • (利用IDEA+Maven)定制属于自己的jar包
  • (转)Sublime Text3配置Lua运行环境
  • (转)编辑寄语:因为爱心,所以美丽
  • .[hudsonL@cock.li].mkp勒索病毒数据怎么处理|数据解密恢复
  • .NET 中使用 TaskCompletionSource 作为线程同步互斥或异步操作的事件
  • .NET单元测试
  • .NET命令行(CLI)常用命令
  • .NET序列化 serializable,反序列化
  • ::
  • @Transactional注解下,循环取序列的值,但得到的值都相同的问题
  • [100天算法】-不同路径 III(day 73)
  • [100天算法】-二叉树剪枝(day 48)
  • [2016.7 Day.4] T1 游戏 [正解:二分图 偏解:奇葩贪心+模拟?(不知如何称呼不过居然比std还快)]