QTextToSpeech 類

QTextToSpeech 類為訪問 TTS (文本轉語音) 引擎提供方便。 更多...

頭: #include <QTextToSpeech>
CMake: find_package(Qt6 REQUIRED COMPONENTS TextToSpeech)
target_link_libraries(mytarget PRIVATE Qt6::TextToSpeech)
qmake: QT += texttospeech
繼承: QObject

公共類型

枚舉類 BoundaryHint { Default, Immediate, Word, Sentence, Utterance }
flags Capabilities
(從 6.6 起) 枚舉類 Capability { None, Speak, PauseResume, WordByWordProgress, Synthesize }
枚舉類 ErrorReason { NoError, Initialization, Configuration, Input, Playback }
enum State { Ready, Speaking, Synthesizing, Paused, Error }

特性

公共函數

QTextToSpeech (QObject * parent = nullptr)
QTextToSpeech (const QString & engine , QObject * parent = nullptr)
(從 6.4 起) QTextToSpeech (const QString & engine , const QVariantMap & params , QObject * parent = nullptr)
virtual ~QTextToSpeech () override
QList<QLocale> availableLocales () const
QList<QVoice> availableVoices () const
QString engine () const
QTextToSpeech::Capabilities engineCapabilities () const
QTextToSpeech::ErrorReason errorReason () const
QString errorString () const
(從 6.6 起) QList<QVoice> findVoices (Args &&... args ) const
QLocale locale () const
double pitch () const
double rate () const
(從 6.4 起) bool setEngine (const QString & engine , const QVariantMap & params = QVariantMap())
QTextToSpeech::State state () const
(從 6.6 起) void synthesize (const QString & text , Functor && functor )
(從 6.6 起) void synthesize (const QString & text , const QObject * context , Functor && functor )
QVoice voice () const
double volume () const

公共槽

(從 6.6 起) qsizetype enqueue (const QString & utterance )
void pause (QTextToSpeech::BoundaryHint boundaryHint = QTextToSpeech::BoundaryHint::Default)
void resume ()
void say (const QString & text )
void setLocale (const QLocale & locale )
void setPitch (double pitch )
void setRate (double rate )
void setVoice (const QVoice & voice )
void setVolume (double volume )
void stop (QTextToSpeech::BoundaryHint boundaryHint = QTextToSpeech::BoundaryHint::Default)

信號

(從 6.6 起) void aboutToSynthesize (qsizetype id )
void engineChanged (const QString & engine )
void errorOccurred (QTextToSpeech::ErrorReason reason , const QString & errorString )
void localeChanged (const QLocale & locale )
void pitchChanged (double pitch )
void rateChanged (double rate )
(從 6.6 起) void sayingWord (const QString & word , qsizetype id , qsizetype start , qsizetype length )
void stateChanged (QTextToSpeech::State state )
void voiceChanged (const QVoice & voice )
void volumeChanged (double volume )

靜態公共成員

QStringList availableEngines ()

詳細描述

使用 say () to start reading text to the default audio device, and stop (), pause (),和 resume () to control the reading of the text.

    connect(ui.speakButton, &QPushButton::clicked, m_speech, [this]{
        m_speech->say(ui.plainTextEdit->toPlainText());
    });
    connect(ui.stopButton, &QPushButton::clicked, m_speech, [this]{
        m_speech->stop();
    });
    connect(ui.pauseButton, &QPushButton::clicked, m_speech, [this]{
        m_speech->pause();
    });
    connect(ui.resumeButton, &QPushButton::clicked, m_speech, &QTextToSpeech::resume);
					

To synthesize text into PCM data for further processing, use synthesize ().

使用 findVoices () to get a list of matching voices, or use availableVoices () to get the list of voices that support the current locale. Change the locale property, using one of the availableLocales () that is a good match for the language that the input text is in, and for the accent of the desired voice output. This will change the list of available voices on most platforms. Then use one of the available voices in a call to setVoice ().

Not every engine supports all features. Use the engineCapabilities () function to test which features are available, and adjust the usage of the class accordingly.

注意: Which locales and voices the engine supports depends usually on the Operating System configuration. E.g. on macOS, end users can install voices through the 可訪問性 panel in System Preferences .

成員類型文檔編製

enum class QTextToSpeech:: BoundaryHint

describes when speech should be stopped and paused.

常量 描述
QTextToSpeech::BoundaryHint::Default 0 Uses the engine specific default behavior.
QTextToSpeech::BoundaryHint::Immediate 1 The engine should stop playback immediately.
QTextToSpeech::BoundaryHint::Word 2 Stop speech when the current word is finished.
QTextToSpeech::BoundaryHint::Sentence 3 Stop speech when the current sentence is finished.
QTextToSpeech::BoundaryHint::Utterance (since Qt 6.6) 4 Stop speech when the current utterance is finished. An utterance is the block of text used in a call to say () 或 enqueue ().

注意: These are hints to the engine. The current engine might not support all options.

[since 6.6] enum class QTextToSpeech:: Capability
flags QTextToSpeech:: Capabilities

This enum describes the capabilities of a text-to-speech engine.

常量 描述
QTextToSpeech::Capability::None 0 The engine implements none of the capabilities.
QTextToSpeech::Capability::Speak 1 << 0 The engine can play audio output from text.
QTextToSpeech::Capability::PauseResume 1 << 1 The engine can pause and then resume the audo output.
QTextToSpeech::Capability::WordByWordProgress 1 << 2 The engine emits the sayingWord () signal for each word that gets spoken.
QTextToSpeech::Capability::Synthesize 1 << 3 The engine can synthesize PCM audio data from text.

該枚舉在 Qt 6.6 引入。

Capabilities 類型是 typedef 對於 QFlags <Capability>。它存儲 Capability 值的 OR 組閤。

另請參閱 engineCapabilities ().

enum class QTextToSpeech:: ErrorReason

This enum describes the current error, if any, of the QTextToSpeech engine.

常量 描述
QTextToSpeech::ErrorReason::NoError 0 沒有齣現錯誤。
QTextToSpeech::ErrorReason::Initialization 1 The backend could not be initialized, e.g. due to a missing driver or operating system requirement.
QTextToSpeech::ErrorReason::Configuration 2 The given backend configuration is inconsistent, e.g. due to wrong voice name or parameters.
QTextToSpeech::ErrorReason::Input 3 The given text could not be synthesized, e.g. due to invalid size or characters.
QTextToSpeech::ErrorReason::Playback 4 Audio playback failed e.g. due to missing audio device, wrong format or audio streaming interruption.

使用 errorReason () to obtain the current error and errorString () to get the related error message.

另請參閱 errorOccurred ().

enum QTextToSpeech:: State

This enum describes the current state of the text-to-speech engine.

常量 描述
QTextToSpeech::Ready 0 The synthesizer is ready to start a new text. This is also the state after a text was finished.
QTextToSpeech::Speaking 1 Text is being spoken.
QTextToSpeech::Synthesizing 4 Text is being synthesized into PCM data. The synthesized() signal will be emitted with chunks of data.
QTextToSpeech::Paused 2 The synthesis was paused and can be resumed with resume ().
QTextToSpeech::Error 3 An error has occurred. Details are given by errorReason ().

另請參閱 QTextToSpeech::ErrorReason , errorReason (),和 errorString ().

特性文檔編製

[since 6.4] engine : QString

This property holds the engine used to synthesize text to speech.

Changing the engine stops any ongoing speech.

On most platforms, changing the engine will update the list of available locales and available voices .

該特性在 Qt 6.4 引入。

訪問函數:

QString engine () const
bool setEngine (const QString & engine , const QVariantMap & params = QVariantMap()) [見下文注意事項]

注意: 此函數可以被援引,通過元對象係統和從 QML。見 Q_INVOKABLE .

通知程序信號:

void engineChanged (const QString & engine )

[read-only, since 6.6] engineCapabilities : const Capabilities

This property holds the capabilities implemented by the current engine

該特性在 Qt 6.6 引入。

訪問函數:

QTextToSpeech::Capabilities engineCapabilities () const

通知程序信號:

void engineChanged (const QString & engine )

另請參閱 engine .

locale : QLocale

This property holds the current locale in use.

By default, the system locale is used.

On some platforms, changing the locale will update the list of available voices , and if the current voice is not available with the new locale, a new voice will be set.

訪問函數:

QLocale locale () const
void setLocale (const QLocale & locale )

通知程序信號:

void localeChanged (const QLocale & locale )

另請參閱 voice and findVoices ().

pitch : double

This property holds the voice pitch, ranging from -1.0 to 1.0.

The default of 0.0 is the normal speech pitch.

訪問函數:

double pitch () const
void setPitch (double pitch )

通知程序信號:

void pitchChanged (double pitch )

rate : double

This property holds the current voice rate, ranging from -1.0 to 1.0.

The default value of 0.0 is normal speech flow.

訪問函數:

double rate () const
void setRate (double rate )

通知程序信號:

void rateChanged (double rate )

[read-only] state : const State

This property holds the current state of the speech synthesizer.

void MainWindow::stateChanged(QTextToSpeech::State state)
{
    switch (state) {
    case QTextToSpeech::Speaking:
        ui.statusbar->showMessage(tr("Speech started..."));
        break;
    case QTextToSpeech::Ready:
        ui.statusbar->showMessage(tr("Speech stopped..."), 2000);
        break;
    case QTextToSpeech::Paused:
        ui.statusbar->showMessage(tr("Speech paused..."));
        break;
    default:
        ui.statusbar->showMessage(tr("Speech error!"));
        break;
    }
    ui.pauseButton->setEnabled(state == QTextToSpeech::Speaking);
    ui.resumeButton->setEnabled(state == QTextToSpeech::Paused);
    ui.stopButton->setEnabled(state == QTextToSpeech::Speaking || state == QTextToSpeech::Paused);
}
					

使用 say () to start synthesizing text with the current voice and locale .

訪問函數:

QTextToSpeech::State state () const

通知程序信號:

void stateChanged (QTextToSpeech::State state )

voice : QVoice

This property holds the voice that will be used for the speech.

The voice needs to be one of the voices available for the engine.

On some platforms, setting the voice changes other voice attributes such as locale , pitch , and so on. These changes trigger the emission of signals.

訪問函數:

QVoice voice () const
void setVoice (const QVoice & voice )

通知程序信號:

void voiceChanged (const QVoice & voice )

另請參閱 findVoices ().

volume : double

This property holds the current volume, ranging from 0.0 to 1.0.

The default value is the platform's default volume.

訪問函數:

double volume () const
void setVolume (double volume )

通知程序信號:

void volumeChanged (double volume )

成員函數文檔編製

[since 6.6] template <typename Functor> void QTextToSpeech:: synthesize (const QString & text , Functor && functor )

[since 6.6] template <typename Functor> void QTextToSpeech:: synthesize (const QString & text , const QObject * context , Functor && functor )

Synthesizes the text into raw audio data.

This function synthesizes the speech asynchronously into raw audio data. When data is available, the functor 將被調用如 functor(QAudioFormat format, QByteArray bytes) ,采用 format describing the format of the data in bytes ; or as functor(QAudioBuffer &buffer) .

The state property is set to Synthesizing when the synthesis starts, and to Ready once the synthesis is finished. While synthesizing, the functor might be called multiple times, possibly with changing values for format .

The functor can be a callable, like a lambda or free function, with an optional context 對象:

tts.synthesize("Hello world", [](const QAudioFormat &format, const QByteArray &bytes){
    // process data according to format
});
					

or a member function of the context 對象:

struct PCMProcessor : QObject
{
    void processData(const QAudioFormat &format, const QByteArray &bytes)
    {
        // process data according to format
    }
} processor;
tts.synthesize("Hello world", &processor, &PCMProcessor::processData);
					

context is destroyed, then the functor will no longer get called.

注意: This API requires that the engine has the Synthesize 能力。

該函數在 Qt 6.6 引入。

另請參閱 say () 和 stop ().

[explicit] QTextToSpeech:: QTextToSpeech ( QObject * parent = nullptr)

Loads a text-to-speech engine from a plug-in that uses the default engine plug-in and constructs a QTextToSpeech object as the child of parent .

The default engine is platform-specific.

If the engine initializes correctly, then the state of the engine will change to QTextToSpeech::Ready ; note that this might happen asynchronously. If the plugin fails to load, then state will be set to QTextToSpeech::Error .

另請參閱 availableEngines ().

[explicit] QTextToSpeech:: QTextToSpeech (const QString & engine , QObject * parent = nullptr)

Loads a text-to-speech engine from a plug-in that matches parameter engine and constructs a QTextToSpeech object as the child of parent .

engine is empty, the default engine plug-in is used. The default engine is platform-specific.

If the engine initializes correctly, the state of the engine will be set to QTextToSpeech::Ready . If the plugin fails to load, or if the engine fails to initialize, the engine's state will be set to QTextToSpeech::Error .

另請參閱 availableEngines ().

[explicit, since 6.4] QTextToSpeech:: QTextToSpeech (const QString & engine , const QVariantMap & params , QObject * parent = nullptr)

Loads a text-to-speech engine from a plug-in that matches parameter engine and constructs a QTextToSpeech object as the child of parent , passing params through to the engine.

engine is empty, the default engine plug-in is used. The default engine is platform-specific. Which key/value pairs in params are supported depends on the engine. See the engine documentation for details. Unsupported entries will be ignored.

If the engine initializes correctly, the state of the engine will be set to QTextToSpeech::Ready . If the plugin fails to load, or if the engine fails to initialize, the engine's state will be set to QTextToSpeech::Error .

該函數在 Qt 6.4 引入。

另請參閱 availableEngines ().

[override virtual noexcept] QTextToSpeech:: ~QTextToSpeech ()

銷毀此 QTextToSpeech object, stopping any speech.

[signal, since 6.6] void QTextToSpeech:: aboutToSynthesize ( qsizetype id )

This signal gets emitted just before the engine starts to synthesize the speech audio for idid is the value returned by a call to enqueue (), Applications can use this signal to make last-minute changes to voice attributes, or to track the process of text enqueued via enqueue ().

該函數在 Qt 6.6 引入。

另請參閱 enqueue (), synthesize (),和 voice .

[static invokable] QStringList QTextToSpeech:: availableEngines ()

Gets the list of supported text-to-speech engine plug-ins.

注意: 此函數可以被援引,通過元對象係統和從 QML。見 Q_INVOKABLE .

另請參閱 engine .

[invokable] QList < QLocale > QTextToSpeech:: availableLocales () const

Returns the list of locales that are supported by the active engine .

注意: 此函數可以被援引,通過元對象係統和從 QML。見 Q_INVOKABLE .

另請參閱 availableVoices () 和 findVoices ().

[invokable] QList < QVoice > QTextToSpeech:: availableVoices () const

Returns the list of voices available for the current locale .

注意: If no locale has been set, the system locale is used.

注意: 此函數可以被援引,通過元對象係統和從 QML。見 Q_INVOKABLE .

另請參閱 availableLocales () 和 findVoices ().

[slot, since 6.6] qsizetype QTextToSpeech:: enqueue (const QString & utterance )

添加 utterance to the queue of texts to be spoken, and starts speaking. Returns the index of the text in the queue, or -1 in case of an error.

If the engine's state is currently Ready , utterance will be spoken immediately. Otherwise, the engine will start to speak utterance once it has finished speaking the current text.

Each time the engine proceeds to the next text entry in the queue, the aboutToSynthesize () signal gets emitted. This allows applications to keep track of the progress, and to make last-minute changes to voice attributes.

調用 stop () clears the queue. To pause the engine at the end of a text, use the Utterance boundary hint.

該函數在 Qt 6.6 引入。

另請參閱 say (), stop (), aboutToSynthesize (),和 synthesize ().

[signal] void QTextToSpeech:: errorOccurred ( QTextToSpeech::ErrorReason reason , const QString & errorString )

This signal is emitted after an error occurred and the state has been set to QTextToSpeech::Error reason parameter specifies the type of error, and the errorString provides a human-readable error description.

QTextToSpeech::ErrorReason 不是注冊 Metatype (元類型),因此,對於隊列化連接而言,必須注冊它采用 Q_DECLARE_METATYPE () 和 qRegisterMetaType ().

另請參閱 errorReason (), errorString (),和 創建自定義 Qt 類型 .

[invokable] QTextToSpeech::ErrorReason QTextToSpeech:: errorReason () const

Returns the reason why the engine has reported an error.

注意: 此函數可以被援引,通過元對象係統和從 QML。見 Q_INVOKABLE .

另請參閱 state and errorOccurred ().

[invokable] QString QTextToSpeech:: errorString () const

Returns the current engine error message.

注意: 此函數可以被援引,通過元對象係統和從 QML。見 Q_INVOKABLE .

另請參閱 errorOccurred ().

[since 6.6] template <typename... Args> QList < QVoice > QTextToSpeech:: findVoices ( Args &&... args ) const

Returns the list of voices that match the criteria in args .

The arguments in args are processed in order to assemble the list of voices that match all of them. An argument of type QString is matched against the name , of the voice, an argument of type QLocale is matched agains the voice's locale , etc. It is possible to specify only the Language or Territory of the desired voices, and the name can be matched against a regular expression .

This function returns all voices if the list of criteria is empty. Multiple criteria of the same type are not possible and will result in a compile-time error.

注意: 除非 args includes the current locale , this function might need to change the locale of the engine to get the list of all voices. This is engine specific, but might impact ongoing speech synthesis. It is therefore advisable to not call this function unless the state is Ready .

該函數在 Qt 6.6 引入。

另請參閱 availableVoices ().

[slot] void QTextToSpeech:: pause ( QTextToSpeech::BoundaryHint boundaryHint = QTextToSpeech::BoundaryHint::Default)

Pauses the current speech at boundaryHint .

是否 boundaryHint is respected depends on the engine .

另請參閱 resume () 和 PauseResume .

[slot] void QTextToSpeech:: resume ()

Resume speaking after pause () 被調用。

注意: On Android, resuming paused speech will restart from the beginning. This is a limitation of the underlying text-to-speech engine.

另請參閱 pause ().

[slot] void QTextToSpeech:: say (const QString & text )

Starts speaking the text .

This function starts sythesizing the speech asynchronously, and reads the text to the default audio output device.

    connect(ui.speakButton, &QPushButton::clicked, m_speech, [this]{
        m_speech->say(ui.plainTextEdit->toPlainText());
    });
					

注意: All in-progress readings are stopped before beginning to read the recently synthesized text.

The current state is available using the state property, and is set to Speaking once the reading starts. When the reading is done, state will be set to Ready .

另請參閱 enqueue (), stop (), pause (), resume (),和 synthesize ().

[signal, since 6.6] void QTextToSpeech:: sayingWord (const QString & word , qsizetype id , qsizetype start , qsizetype length )

此信號發射,當 word , which is the slice of text indicated by start and length in the utterance id , gets played to the audio device.

注意: This signal requires that the engine has the WordByWordProgress 能力。

該函數在 Qt 6.6 引入。

另請參閱 Capability and say ().

[invokable, since 6.4] bool QTextToSpeech:: setEngine (const QString & engine , const QVariantMap & params = QVariantMap())

Sets the engine used by this QTextToSpeech 對象到 engine , passing params through to the engine constructor.

返迴是否 engine could be set successfully.

Which key/value pairs in params are supported depends on the engine. See the engine documentation for details. Unsupported entries will be ignored.

注意: 此函數可以被援引,通過元對象係統和從 QML。見 Q_INVOKABLE .

注意: setter 函數對於特性 engine .

該函數在 Qt 6.4 引入。

另請參閱 engine ().

[slot] void QTextToSpeech:: stop ( QTextToSpeech::BoundaryHint boundaryHint = QTextToSpeech::BoundaryHint::Default)

Stops the current reading at boundaryHint , and clears the queue of pending texts.

The reading cannot be resumed. Whether the boundaryHint is respected depends on the engine.

另請參閱 say (), enqueue (),和 pause ().