Дмитрий
ДмитрийJuly 10, 2017, 3:19 a.m.

Using QtTextToSpeech for speech synthesis

The Qt 5.8.0 library provided programmers with the ability to use a systemic speech synthesizer. A speech synthesizer is a program that converts text to speech. Speech synthesizers are an integral part of any modern operating system: Windows (version 7 and higher), Mac OS, Linux, iOS and Android. Cross-platform interface for managing speech synthesis provides QtTextToSpeech module Qt library.

To work with the QtTextToSpeech module on Windows OS, you must:

  • Install the Qt library with the QtTextToSpeech module for the Visual Studio 2015 compiler or older (mingw will not work);
  • Install the Visual Studio 2015 compiler;
  • Install the SAPI 5.1 library if, for some reason, it is not on your computer;
  • установить голоса для синтезатора речи (если у вас они отсутствуют).
  • При сборке проекта необходимо использовать теневую сборку.

Description

If you compile the program, you see a message

Error loading text-to-speech plug-in "sapi"

то вы сделали что-то неправильно.

then you did something wrong.

If you use Android, then by default you have an online synthesizer. For this you will pay a delay in the synthesis and spent traffic. If this does not suit you, then install the offline version. On Android 5.1, for this you need to go to "settings" - "special features" - "speech synthesis" - "Google speech synthesizer" - "voice data installation" - "Russian (Russia)" and click install and wait for completion. In addition, we prepare Qt Creator for creating Android applications.

Now you can start writing the program. Under the link you can download the project with the source code of the program described below. Create a new qtwidget project. In the project file, connect the necessary module

QT += texttospeech

We connect the synthesizer library of speech

#include <QtTextToSpeech>

Create a pointer to a QTextToSpeech class object

QTextToSpeech* speech;

And then the object itself

speech = new QtextToSpeech;

Now you can generate speech signals using the say () function, as the argument of which you need to convey the spoken text. The examples created by Qt Creator developers include a simple helloSpeech example. Consider it in order to better understand the capabilities of the module in question.

I'll move on to some more complicated things. The program, which you can download by reference, contains a widget of the Q TextEdit class for playback text, control buttons: start, stop, forward, ..., a window for selecting files, and windows for setting the synthesizer.

void MainWindow::start(bool checked)

You can also play large text fragments for playback. However, this leads to unnecessary delays, and in the case of the online synthesizer on Android and to the hang of the program. Therefore, we break the text into fragments, the less, the better. First, I select the paragraph (int activeBlock) from the text and then break the line into a sheet of lines (QStringList readList) using the dots as a separator.

void MainWindow::start(bool checked)
{
    if(checked)
    {
        if(readList.isEmpty())
        {
            readList = ui->textEdit->document()->findBlockByNumber( activeBlock ).text().split(".");
        }
        if(!readList.isEmpty())
        {
            readString = readList.first();
            readList.removeFirst();
            if(!readString.contains(QRegularExpression("[A-Z]|[a-z]|[0-9]|[А-Я]|[а-я]")))
            {
                readString = ".";
                if(QSysInfo::productType() == "android")
                    readString = " ";
            }
            speech->say( readString );
            scrollTo();
            ui->textEdit->setReadOnly(true);
        }
    }
    else
    {
        readList.prepend(readString);//
        speech->stop();
        ui->textEdit->setReadOnly(false);
    }
}

void MainWindow::speechStateChange(QTextToSpeech::State state)

One line is sent to the synthesizer. Upon completion of its playback, speech generates a stateChanged signal. The speechStateChange slot connected to it is responsible for playing the next line.

void MainWindow::speechStateChange( QTextToSpeech::State state)
{
    QString mes;
    switch(state)
    {
    case QTextToSpeech::Ready:
        if(ui->pushButtonStart->isChecked())
        {
            textBlockSelection(colorClean);
            if(readList.isEmpty())
            {
                if( setActiveBlock( activeBlock+1 ) )
                    start();
                else
                    stop();
            }
            else
            {
                start();
            }
        }
        mes = "ready";
        break;
    case QTextToSpeech::Speaking:
        textBlockSelection(Qt::green);
        mes = "speaking";
        break;
    case QTextToSpeech::Paused:
        mes = "paused";
        break;
    case QTextToSpeech::BackendError:
        mes = "error";
        break;
    }
}

Secondary functions

For the convenience of using the program as a reader, two auxiliary functions scrollTo () were written to scroll the text to the selected paragraph and textBlockSelection (QColor) to highlight the readable paragraph with the background color. Below is their source code.

void MainWindow::scrollTo()

void MainWindow::scrollTo()
{
    if(ui->textEdit->verticalScrollBar()->maximum() == 0)
        return;
    QTextDocument *textDoc = ui->textEdit->document();
    int value = 0;
    for(int i = 0; i < activeBlock; i++)
    {
        value +=textDoc->findBlockByNumber(i).layout()->lineCount()
                * textDoc->findBlockByNumber(i).layout()->lineAt(0).height()
                + textDoc->findBlockByNumber(i).blockFormat().bottomMargin();
    }
    if(value <= ui->textEdit->verticalScrollBar()->maximum())
        ui->textEdit->verticalScrollBar()->setValue(value);
}

bool MainWindow::setActiveBlock(int blockNumber, bool scroll)

bool MainWindow::setActiveBlock(int blockNumber, bool scroll)
{
    readList.clear();
    textBlockSelection(colorClean);
    if(blockNumber < 0)
    {
        activeBlock = 0;
        if(scroll)
            scrollTo();
        return false;
    }
    if(blockNumber >= ui->textEdit->document()->blockCount())
    {
        activeBlock = ui->textEdit->document()->blockCount()-1;
        if(scroll)
            scrollTo();
        return false;
    }
    else
    {
        activeBlock = blockNumber;
        if(scroll)
            scrollTo();
        return true;
    }
}

Emphasis and Homographs

An important problem for a speech synthesizer is stress. Especially in cases where two words are written equally, but have different stresses (omographs). In this case, without the use of complex semantic algorithms, stress can only be set manually. And Windows (unlike Android) allows you to do this. To do this, put a "` "(on one key with the letter e). However, it was not possible to establish the exact mechanism of operation of this tool.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Дмитрий
  • July 23, 2017, 2:52 a.m.

Если вы знаете простой способ для извлечения текста из pdf или djv файлов напишите в ответе.

Evgenii Legotckoi
  • July 23, 2017, 6:10 a.m.

Лично я простого не знаю способа. В обоих случаях понадобится использовать сторонние библиотеки.

В случае с pdf - это будет либа, которая работает с pdf, какой-нибудь poppler-qt.
В случае же с djvu - это уже либа по распознаванию текста в изображениях.
Но за пример такой работы ничего не скажу, не занимался таким.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
l
  • laei
  • April 23, 2024, 4:19 p.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:10points,
  • Rating points-10
l
  • laei
  • April 23, 2024, 4:17 p.m.

C++ - Тест 003. Условия и циклы

  • Result:50points,
  • Rating points-4
e
  • ehot
  • March 31, 2024, 9:29 p.m.

C++ - Тест 003. Условия и циклы

  • Result:78points,
  • Rating points2
Last comments
k
kmssrFeb. 9, 2024, 2:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 6:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 4:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 5:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 12:46 p.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 2:45 p.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 1:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 9:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 11:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks