Qt文档阅读笔记-Hello Speak Example

news/2024/7/7 20:22:06

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

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);
}

http://lihuaxi.xjx100.cn/news/104559.html

相关文章

MySQL 8.0 OCP(1Z0-908)中文题库解析

作者介绍&#xff1a;姚远&#xff0c;Oracle ACE&#xff08;Oracle和MySQL数据库方向&#xff09;&#xff0c;华为云MVP&#xff0c;《MySQL 8.0运维与优化》的作者。中国第一个Oracle高可用大师&#xff0c;拥有包括 Oracle 10g和12c OCM在内的20数据库相关认证。曾任IBM公…

科比,老大1000天

不知不觉&#xff0c;老大已经走了1000天了&#xff0c;正好这个星期的数据分析的课就是科比投篮可视化&#xff0c;让我一起来分享一下吧。 对照列表机翻,仅供参考 action_type 进攻方式&#xff08;更具体&#xff09; combined_shot_type 进攻方式 game_event_id 比赛时…

leetcode88. 合并两个有序数组

不用辅助数组的做法&#xff0c;就是从后往前放&#xff0c;因为已经排好序了&#xff0c;双指针从后往前 def merge(self, nums1, m, nums2, n): “”" :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, …

策略分析中缺失值的处理方法

在日常的策略分析中&#xff0c;经常会碰到分析的变量出现缺失值的情况&#xff0c;如果对这些缺失值视而不见&#xff0c;则会对策略分析的结果造成一定的影响。那么我们如何处理缺失值呢&#xff1f;关注“金科应用研院”&#xff0c;回复“CSDN”领取“风控资料合集” 首先…

外汇天眼:英国将在 2023 年进入衰退?

经济学家警告说&#xff0c;英国将在 2023 年夏季之前进入衰退。 从 10 月到明年 6 月&#xff0c;英国经济预计每季度萎缩 0.2% 左右。 安永&#xff08;The EY ITEM Club&#xff09;一家总部位于英国的经济预测组织。在其秋季预测中预测&#xff0c;这种长期的经济下滑将导…

基于Vue2的antDesign组件总结

基于Vue2的antDesign组件总结表格组件a-table一、带复选框的表格&#xff0c;用户点击按钮&#xff0c;实现选择的复选框清空二、点击表头排序触发接口最终&#xff1a;表格组件的开发bug总结一、样式二、逻辑a-pagination分页组件一、分页控件英文显示的问题二、分页组件的分页…

Hr常问面试题总结

前言 秋招也告一段落&#xff0c;总结一下秋招中Hr常问的面试题 你期望的薪资 offershow查历年的情况&#xff0c;答一个sp左右的钱&#xff0c;并且加上我有足够的信息可以胜任这个职位 你还有什么问题要问么&#xff1f; 公司的培养体系、晋升路线是什么样子的&#xff1…

Linux学习-13-Linux文本处理命令(cat、more、head、less、tail、grep)

6 Linux文本处理命令1&#xff08;cat、more、head、less、tail、grep&#xff09; Linux 中&#xff0c;文本处理无非是对文本内容做查看、修改等操作。Linux中的文本处理命令,可以实现对文本内容做自动化的处理&#xff0c;而不是手工处理 6.1 cat命令&#xff1a;连接文件…