Дмитрий
Дмитрий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
AD

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

  • Result:50points,
  • Rating points-4
m

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

  • Result:80points,
  • Rating points4
m

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

  • Result:20points,
  • Rating points-10
Last comments
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 7:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 2:19 p.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 1:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 5:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
k
kmssrFeb. 9, 2024, 12:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiJune 24, 2024, 9:11 p.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 12:04 p.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 9:49 a.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…
9
9AnonimOct. 25, 2024, 3:10 p.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks