《Qt5+语音功能(QTextToSpeech类)》

在Qt中QTextToSpeech类提供了文本转语音引擎,使用say()函数合成文本,使用setLocale()指定语言环境,使用setRate()函数设置语速,使用setPitch()函数设置音高,使用setVolume()函数设置音量。

 

简单示例 


1、打开Qt,新建一个Qt Widgets Application项目,在pro文件中添加QT += texttospeech,添加头文件#include "QTextToSpeech"

pro文件

#-------------------------------------------------
#
# Project created by QtCreator 2018-11-27T21:52:02
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
QT += texttospeech
TARGET = QTextToSpeech
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0


SOURCES += \
        main.cpp \
        mainwindow.cpp

HEADERS += \
        mainwindow.h

FORMS += \
        mainwindow.ui

2、然后在mainwindow.cpp中添加代码

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QTextToSpeech"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QTextToSpeech *tts = new QTextToSpeech(this);
    tts->setLocale(QLocale::Chinese);//设置语言环境
    tts->setRate(0.0);//设置语速-1.0到1.0
    tts->setPitch(1.0);//设置音高-1.0到1.0
    tts->setVolume(1.0);//设置音量0.0-1.0
    if(tts->state()==QTextToSpeech::Ready)
    {
        for(int i=0;i<10;i++)
        {
            if(i==5)
            {
                tts->stop();//停止语音
            }
            else
            {
                tts->say("北京欢迎你");//开始合成文本
            }
        }
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

 

Qt官方示例 


代码实现功能:

  1. 选择引擎
  2. 选择语言
  3. 选择声音类型
  4. 设置音高、音速、音量
  5. 阅读、暂停、继续、停止
/****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of The Qt Company Ltd nor the names of its
**     contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/



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

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
    m_speech(0)
{
    ui.setupUi(this);
    setWindowTitle("语音播报");
    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();
}
/*设置语速-1.0到1.0*/
void MainWindow::setRate(int rate)
{
    m_speech->setRate(rate / 10.0);
}
/*设置音高-1.0到1.0*/
void MainWindow::setPitch(int pitch)
{
    m_speech->setPitch(pitch / 10.0);
}
/*设置音量0.0-1.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);
}

显示效果

 

完整代码


Qt官方示例完整代码下载链接:https://pan.baidu.com/s/1ryMHLF_d0sAlLPPyoFBYfQ 
提取码:iqt3 

 

 

  • 14
    点赞
  • 71
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
Qt5是一款流行的跨平台应用程序开发框架,而Ogre13.6是一个功能强大的开源图形引擎。这两者可以结合使用,以实现高质量的3D图形渲染和交互式应用程序的开发。 Qt5提供了丰富的GUI控件库和功能模块,可以方便地构建用户友好的界面,并处理用户输入和事件。它还提供了信号槽机制,能够方便地实现模块之间的通信和交互。Qt5还具有跨平台的优势,可以在不同的操作系统上运行和开发。 Ogre13.6是一款面向实时图形渲染的引擎,它支持各种不同的平台和图形硬件。Ogre13.6提供了强大的渲染功能和灵活的扩展性,可以实现复杂的特效和真实感的渲染。它还支持多种文件格式的模型和纹理导入,并提供了各种渲染技术的实现。 在将Qt5与Ogre13.6结合使用时,可以通过Qt5提供的OpenGL模块来集成Ogre13.6的渲染功能Qt5的OpenGL模块提供了与Ogre13.6兼容的OpenGL API,可以将Ogre13.6引擎渲染的结果显示在Qt5的窗口。此外,Qt5还提供了QOpenGLWidget,可以方便地将Ogre13.6的渲染结果嵌入到Qt5应用程序的界面。 通过结合使用Qt5和Ogre13.6,开发者可以利用Qt5的丰富功能和跨平台优势,快速构建交互式的3D应用程序。他们可以利用Ogre13.6的强大渲染功能和扩展性,实现高质量的图形渲染效果。无论是开发游戏、虚拟现实应用程序还是其他需要图形渲染的应用,Qt5和Ogre13.6的结合都能为开发者提供便利和灵活性。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值