在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官方示例
代码实现功能:
- 选择引擎
- 选择语言
- 选择声音类型
- 设置音高、音速、音量
- 阅读、暂停、继续、停止
/****************************************************************************
**
** 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