目录

Text to Speech

API Declaration

Add the following configuration to the features attribute in the manifest.json file:

{"name": "service.texttoaudio"}

Modules Import

Add the following configuration to the script element on the page where the API will be called:

import texttoaudio from '@service.texttoaudio'

Or

var texttoaudio = require("@service.texttoaudio")

Application Scope

Item

Description

Applicable devices

Mobile phones and tablets

Applicable regions

Global

Definition

API

Description

texttoaudio.speak(OBJECT)

Adds the text to be processed by the TTS engine in the queue.

texttoaudio.textToAudioFile(OBJECT)

Converts the text in the queue to the voice file.

texttoaudio.isLanguageAvailable(OBJECT)

Checks whether the TTS engine of the device supports the input language.

texttoaudio.onttsstatechange = function(data)

Listens to the status change of the specified operation ID. The parameter can be:

  • onStart
  • onStop
  • onError
  • onDone

texttoaudio.stop()

Stops the voice playing or saves the voice to the file, and removes the voice in the queue.

texttoaudio.isSpeaking()

Checks whether the TTS engine is playing voice.

[h2]texttoaudio.speak(OBJECT)

Description

Adds the text to be processed by the TTS engine in the queue.

OBJECT

Parameter

Type

Mandatory

Description

lang

string

Yes

Text language, for example, zh_CN (simplified Chinese) and en_US (English).

content

string

Yes

Text content. The content can contain a maximum of 4,000 characters.

rate

number

No

Speech speed. The value should be greater than 0. 0.5 indicates half speed, and 2 indicates twice speed. If the value of this parameter is not set, the default value 1 will be used. The value range varies according to the TTS engines. If the value exceeds the boundary, the boundary value is used.

pitch

number

No

Pitch. The value should be greater than 0. A larger value indicates a higher pitch. If the value of this parameter is not set, the default value 1 will be used. The value range varies according to the TTS engines. If the value exceeds the boundary, the boundary value is used.

success

function

No

Callback upon success.

fail

function

No

Callback upon failure.

Parameters returned by success

Parameter

Type

Description

utteranceId

string

Unique ID of an operation.

Result codes returned by fail

Result Code

Description

1000

The voice play failed.

1001

Not supported by the system version.

1002

Initialization failure.

1003

Text length exceeds the upper limit.

1004

The language is not supported.

Sample Code

texttoaudio.speak({
  lang:'en_US',
  content:'I like chocolate.',
  pitch:1.0,
  rate:1.0,
  success:function(data) {
    console.log('speak.success --> utteranceId: ' + data.utteranceId);
  },
  fail:function(errorMessage, errorCode) {
    console.log('speak.fail --> errorMessage: ' + errorMessage + ", errorCode: " + errorCode);
  }
});

[h2]texttoaudio.textToAudioFile(OBJECT)

Description

Converts the text in the queue to the voice file. To accurately detect errors and track speech synthesis, you are advised to set onTtsStateChange.

OBJECT

Parameter

Type

Mandatory

Description

lang

string

Yes

Text language, for example, zh_CN (simplified Chinese) and en_US (English).

content

string

Yes

Text content. The content can contain a maximum of 4,000 characters.

rate

number

No

Speech speed. The value should be greater than 0. 0.5 indicates half speed, and 2 indicates twice speed. If the value of this parameter is not set, the default value 1 will be used. The value range varies according to the TTS engines. If the value exceeds the boundary, the boundary value is used.

pitch

number

No

Pitch. The value should be greater than 0. A larger value indicates a higher pitch. If the value of this parameter is not set, the default value 1 will be used. The value range varies according to the TTS engines. If the value exceeds the boundary, the boundary value is used.

success

function

No

Callback upon success.

fail

function

No

Callback upon failure.

Parameters returned by success

Parameter

Type

Description

filePath

string

File path for saving generated files.

utteranceId

string

Unique ID of an operation.

Result codes returned by fail

Result Code

Description

1000

TTS failed.

1001

Not supported by the system version.

1002

Initialization failure.

1003

Text length exceeds the upper limit.

1004

The language is not supported.

1005

I/O exception.

Sample code

texttoaudio.onttsstatechange = function(data) {
  switch (data.state) {
    case'onStart':
      console.log('onttsstatechange --> Synthesis(' + data.utteranceId + ') started.');
      break;
    case'onError':
      console.log('onttsstatechange --> Synthesis(' + data.utteranceId + ') failed.');
      break;
    case'onStop':
      console.log('onttsstatechange --> Synthesis(' + data.utteranceId + ') stopped.');
      break;
    case'onDone':
      console.log('onttsstatechange --> Synthesis(' + data.utteranceId + ') done.');
      break;
    default:
      break;
  }
}
texttoaudio.textToAudioFile({
  lang:'en_US',
  content:'I am running by the lake.',
  pitch:1.0,
  rate:1.0,
  success:function(data) {
    // Utterance is successfully added to TTS engine's queue. Make sure that onttsstatechange is 
    // triggered with 'onDone' to start using the generated audio file.
    console.log('success --> utteranceId: ' + data.utteranceId + ", filePath: " + data.filePath);
  },
  fail:function(errorMessage, errorCode) {
    console.log('fail --> errorMessage: ' + errorMessage + ", errorCode: " + errorCode);
  }
});

[h2]texttoaudio.isLanguageAvailable(OBJECT)

Description

Checks whether the TTS engine of the device supports the input language.

OBJECT

Parameter

Type

Mandatory

Description

lang

string

Yes

Text language, for example, zh_CN (simplified Chinese) and en_US (English).

success

function

No

Callback upon success.

fail

function

No

Callback upon failure.

Parameters returned by success

Parameter

Type

Description

isAvailable

string

If the language is supported, the value is true. Otherwise, the value is false.

Result codes returned by fail

Result Code

Description

200

Common error.

202

Invalid parameter.

Sample Code

texttoaudio.isLanguageAvailable({
  lang:'tr', 
  success:function(data) {
    console.log('success --> isAvailable: ' + data.isAvailable);
  },
  fail:function(errorMessage, errorCode) {
    console.log('fail --> errorMessage: ' + errorMessage + ', errorCode: ' + errorCode);
  }});

[h2]texttoaudio.onttsstatechange = function(data)

Description

Listens to the status change of each operation. The statuses are onStart, onStop, onError, and onDone.

Returns

Parameter

Type

Description

utteranceId

string

Unique ID of an operation.

state

string

Status of the operation. The value can be onStart, onStop, onError, or onDone.

Sample code

texttoaudio.onttsstatechange = function(data) {
  switch (data.state) {
    case'onStart':
      console.log('onttsstatechange --> Synthesis(' + data.utteranceId + ') started.');
      break;
    case'onError':
      console.log('onttsstatechange --> Synthesis(' + data.utteranceId + ') failed.');
      break;
    case'onStop':
      console.log('onttsstatechange --> Synthesis(' + data.utteranceId + ') stopped.');
      break;
    case'onDone':
      console.log('onttsstatechange --> Synthesis(' + data.utteranceId + ') done.');
      break;
    default:
      break;
  }}

[h2]texttoaudio.stop()

Description

Stops the voice playing or saves the voice to the file, and removes the voice in the queue.

Returns

Returns

Description

0

The request is successful.

-1

Request failed.

Sample Code

var value = texttoaudio.stop();
if(value === 0) {
  console.log('stop --> success');
} else {
  console.log('stop --> fail');
}

[h2]texttoaudio.isSpeaking()

Description

Checks whether the TTS engine is playing or synthesizing voice.

Returns

Returns

Description

true

The TTS engine is playing or synthesizing the voice.

false

The TTS engine is not playing or synthesizing the voice.

Sample Code

var result = texttoaudio.isSpeaking();
console.log('isSpeaking --> ' + result);

Demo

<template>
  <div class="container">
    <div class="item-container">
      <input class="btn" type="button" value="Speak" onclick="Speak" />
    </div>
    <div class="item-container">
      <input class="btn" type="button" value="textToAudioFile" onclick="textToAudioFile" />
    </div>
    <div class="item-container">
      <input class="btn" type="button" value="isLanguageAvailable" onclick="isLanguageAvailable" />
    </div>
    <div class="item-container">
      <input class="btn" type="button" value="stop " onclick="stop " />
    </div>

    <div class="item-container">
      <input class="btn" type="button" value="isSpeaking " onclick="isSpeaking " />
    </div> 

  </div>
</template> 
<style>
.container{
  flex: 1;
  flex-direction: column;
}
.item-container {
  margin-left: 32px;
  margin-right:32px;
  padding-top: 20px;
  padding-right: 20px;
  padding-bottom: 20px;
  padding-left: 20px;
  background-color: #fff;
  border-radius: 32px;
  flex-direction: column;
}
  .btn {
    background-color: #0faeff;
    color: #ffffff; 
    width:600px;
    height: 100px;
    font-size: 50px;
    border-radius:15px;
  }
</style> 
<script> 
    import texttoaudio from '@service.texttoaudio'
    import prompt from '@system.prompt';
    export default {
        data: {
            componentName: 'texttoaudio',
            isRefreshing: false,
            enableRefresh: true
        },
        onInit() {
            this.$page.setTitleBar({ text: 'texttoaudio' })
            texttoaudio.onttsstatechange = function (data) {
                switch (data.state) {
                    case 'onStart':
                        console.log('onttsstatechange --> Synthesis(' + data.utteranceId + ') started.');
                        break;
                    case 'onError':
                        console.log('onttsstatechange --> Synthesis(' + data.utteranceId + ') failed.');
                        break;
                    case 'onStop':
                        console.log('onttsstatechange --> Synthesis(' + data.utteranceId + ') stopped.');
                        break;
                    case 'onDone':
                        console.log('onttsstatechange --> Synthesis(' + data.utteranceId + ') done.');
                        break;
                    default:
                        break;
                }
            }
        },
        Speak() {
            texttoaudio.speak({
                lang: 'en_US',
                //content: 'I like chocolate.',
                content: "internal://files/Music/TTS/tts_20211220100300690.wav",
                pitch: 1.0,
                rate: 1.0,
                success: function (data) {
                    console.log('speak.success --> utteranceId: ' + data.utteranceId);
                },
                fail: function (errorMessage, errorCode) {
                    console.log('speak.fail --> errorMessage: ' + errorMessage + ", errorCode: " + errorCode);
                }
            });
        },

        textToAudioFile() {
            texttoaudio.textToAudioFile({
                lang: 'en_US',
                content: 'I am running by the lake.',
                pitch: 1.0,
                rate: 1.0,
                success: function (data) {
                    // Utterance is successfully added to TTS engine's queue. Make sure that onttsstatechange is  
                    // triggered with 'onDone' to start using the generated audio file. 
                    console.log('success --> utteranceId: ' + data.utteranceId + ", filePath: " + data.filePath);
                    prompt.showToast({
                        message:  'utteranceId:'+ data.utteranceId+'  ,filePath: '+data.filePath,
                        duration: 2000,
                        gravity: 'bottom'
                    });
                },
                fail: function (errorMessage, errorCode) {
                    console.log('fail --> errorMessage: ' + errorMessage + ", errorCode: " + errorCode);
                }
            });
        },
        isLanguageAvailable() {
            texttoaudio.isLanguageAvailable({
                lang: 'tr',
                success: function (data) {
                    console.log('success --> isAvailable: ' + data.isAvailable);
                    prompt.showToast({
                        message: data.isAvailable,
                        duration: 2000,
                        gravity: 'bottom'
                    });
                },
                fail: function (errorMessage, errorCode) {
                    console.log('fail --> errorMessage: ' + errorMessage + ', errorCode: ' + errorCode);
                }
            });

        },
        onttsstatechange() {
            texttoaudio.onttsstatechange = function (data) {
                switch (data.state) {
                    case 'onStart':
                        console.log('onttsstatechange --> Synthesis(' + data.utteranceId + ') started.');
                        break;
                    case 'onError':
                        console.log('onttsstatechange --> Synthesis(' + data.utteranceId + ') failed.');
                        break;
                    case 'onStop':
                        console.log('onttsstatechange --> Synthesis(' + data.utteranceId + ') stopped.');
                        break;
                    case 'onDone':
                        console.log('onttsstatechange --> Synthesis(' + data.utteranceId + ') done.');
                        break;
                    default:
                        break;
                }
            }
        },  
        stop() {
            var value = texttoaudio.stop();
            if (value === 0) {
                console.log('stop --> success');
            } else {
                console.log('stop --> fail');
            }
        },
        isSpeaking() {
            var result = texttoaudio.isSpeaking();
            console.log('isSpeaking --> ' + result);
        }
    }
</script>

The following figure shows the final effect.

Version Change History

Version

Date

Description

1080

2021-12-28

First official release.