Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting
TIMEWEB

Using QtTextToSpeech for speech synthesis

qttexttospeech, Qt, синтезатор речи, qt speech, qt читалка

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;
  • Set the voice for the speech synthesizer (if you do not have one).
  • Set the voice for the speech synthesizer (if you do not have one)....

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.

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 = ".";//windows не читает точки
                if(QSysInfo::productType() == "android")
                    readString = " ";
            }
            speech->say( readString );
            scrollTo();
            ui->textEdit->setReadOnly(true);
        }
    }
    else
    {
        readList.prepend(readString);//
        speech->stop();
        ui->textEdit->setReadOnly(false);
    }
}

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()
{
    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)
{
    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.

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

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

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
P
Feb. 18, 2019, 3:39 p.m.
Poyar

C++ - Test 001. The first program and data types

  • Result:73points,
  • Rating points1
НБ
Feb. 15, 2019, 1:03 p.m.
Николай Булахтин

C++ - Test 002. Constants

  • Result:25points,
  • Rating points-10
Last comments
V
Feb. 14, 2019, 6:41 p.m.
Vlad15007

Спасибо огромное! Заработало!
А
Feb. 12, 2019, 9:26 a.m.
Александр90

Сам разборался, спасибо.
А
Feb. 12, 2019, 8:19 a.m.
Александр90

День добрый! Можешь выложить форму mainwindow.ui от урока? Заранее спасибо
Feb. 11, 2019, 10:51 a.m.
Евгений Легоцкой

Нет, у меня проблема с жёстким диском случилась, занимался восстановлением ПК, ещё пару вечеров придётся этим заниматься, увы.
Now discuss on the forum
Feb. 17, 2019, 5:28 p.m.
Евгений Легоцкой

Добрый день. Очень извиняюсь за долгий ответ Первое, что нашёл, так это необходимость перерисовать чекбокс. void CheckBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem ...
Feb. 15, 2019, 3:36 p.m.
Евгений Легоцкой

Ну я тут нашёл одно решение, но сам его не проверял. Вам нужно помещать фамилии скорее всего в ячейки заголовка, и потом просто перерисовывать их QHeaderView * header = m_ui->tableWidget...
Feb. 15, 2019, 7:53 a.m.
Евгений Легоцкой

Добрый день! Не работал с remoteobjects, поэтому глянул документацию, чтобы рассмотреть, что это за зверь. После просмотра документации сложилось стойкой впечатление, что это вполне возм...
m
Feb. 14, 2019, 6:28 p.m.
mr_roman

Нашел решение на Java. Удалось интегрировать в проект сервиса на Qt, теперь из Qt запускаю Java-код акселерометра.
Join us in social networks

For registered users on the site there is a minimum amount of advertising