Ionic Text to Speech: How to Convert Text to Speech in Ionic Application using Ionic Native and Cordova Plugins (Có thử tiếng Việt ok)

Table of Contents

Ionic Text to Speech: How to Convert Text to Speech in Ionic Application using Ionic Native and Cordova Plugins (Có thử tiếng Việt ok)

Setting Up Ionic Environment

npm install -g @ionic/cli ionic start ionic-texttospeech-example blank --type=angular

image

Install Text to Speech Plugin

ionic cordova plugin add cordova-plugin-tts
npm install @ionic-native/text-to-speech

image

app.module.ts

In the next step, we need to import and register the TextToSpeech plugin in Ionic’s main app.module.ts file.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

import { TextToSpeech } from '@ionic-native/text-to-speech/ngx';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    TextToSpeech
  ],
  bootstrap: [AppComponent]
})

export class AppModule {}

Implement Text to Speech in Ionic

Go to the app folder and open the home.page.ts file; replace the code with the below code.

import { Component } from '@angular/core';
import { TextToSpeech } from '@ionic-native/text-to-speech/ngx';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})

export class HomePage {

  Text = [];

  constructor(
    private textToSpeech: TextToSpeech
  ) {
    this.Text = [
      "Things are going well so far",
      "That's the last straw",
      "The best of both worlds",
      "The person we were just talking about showed up!"      
    ]
  }


  convertTextToSpeech(text) {
    this.textToSpeech.speak(text)
      .then(
        () => console.log('Done')
      )
      .catch((reason: any) => console.log(reason));
  }

}

You have to import TextToSpeech service from ‘@ionic-native/text-to-speech/ngx’ at the top of the component.

Inject TextToSpeech service in constructor object.

Define a Text array; you can add as many as text para.

The convertTextToSpeech() method takes the text argument, access the speak() method, and pass the text, which needs to be converted to speech.

Add the following code in home.page.html file:

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Ionic Text to Speech Demo
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <ion-list>
    <ion-item-sliding *ngFor="let text of Text">
      <ion-item>
        <ion-label text-wrap>{{text}}</ion-label>
      </ion-item>
      <ion-item-options side="end">
        <ion-item-option (click)="convertTextToSpeech(text)"><ion-icon name="mic-outline"></ion-icon></ion-item-option>
      </ion-item-options>
    </ion-item-sliding>
  </ion-list>
</ion-content>

The sliding panel of ionic bound with *ngFor loop and iterating every text para can slide towards the right and click on the mic icon to listen to your text.

Setting Up Text to Speech

Additionally, you can adjust the text to speech with some of the properties that allow you to add a particular language and handle the speech’s pace via rate prop.

import { Component } from '@angular/core';
import { TextToSpeech } from '@ionic-native/text-to-speech/ngx';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})

export class HomePage {

  Text = [];

  constructor(private textToSpeech: TextToSpeech) {
    this.Text = [
      "Things are going well so far",
      "That's the last straw",
      "The best of both worlds",
      "The person we were just talking about showed up!"      
    ]
  }

  convertTextToSpeech(text) {
      this.textToSpeech.speak({
        text: text,
        locale: 'en-GB',
        rate: 0.75
    })
    .then(() => 
      console.log('Done')
    )
    .catch((reason: any) => 
      console.log(reason)
    );
  }

}

Test Application

In general, testing should be done in a real device; however, we are testing it regardless of the local environment.

ionic cordova platform add ios
ionic cordova platform add android

Run the command based on your preference:

# iOS
ionic cordova run ios

# Android
ionic serve --devapp

ionic cordova run android -l -c

edge://inspect/#devices

image

Summary

we have seen how easy it is to integrate text to speech in the Ionic application. However, we have seen just the tip of the iceberg; you can customize it in many ways as per your requirement, i hope you liked it.


Thử tiếng Việt

Get available locales for text to speech (TTS)

https://stackoverflow.com/questions/4872702/get-available-locales-for-text-to-speech-tts

[ar, ar_EG, bg, bg_BG, ca, ca_ES, cs, cs_CZ, da, da_DK, de, de_AT, de_BE, de_CH, de_DE, de_LI, de_LU, el, el_CY, el_GR, en, en
_AU, en_BE, en_BW, en_BZ, en_CA, en_GB, en_HK, en_IE, en_IN, en_JM, en_MH, en_MT, en_NA, en_NZ, en_PH, en_PK, en_RH, en_SG, en_TT, en_US, en_US_POSIX,
 en_VI, en_ZA, en_ZW, es, es_AR, es_BO, es_CL, es_CO, es_CR, es_DO, es_EC, es_ES, es_GT, es_HN, es_MX, es_NI, es_PA, es_PE, es_PR, es_PY, es_SV, es_US
, es_UY, es_VE, et, et_EE, eu, eu_ES, fa, fa_IR, fi, fi_FI, fr, fr_BE, fr_CA, fr_CH, fr_FR, fr_LU, fr_MC, gl, gl_ES, hr, hr_HR, hu, hu_HU, in, in_ID,
is, is_IS, it, it_CH, it_IT, iw, iw_IL, ja, ja_JP, kk, kk_KZ, ko, ko_KR, lt, lt_LT, lv, lv_LV, mk, mk_MK, ms, ms_BN, ms_MY, nl, nl_BE, nl_NL, no, no_N
O, no_NO_NY, pl, pl_PL, pt, pt_BR, pt_PT, ro, ro_RO, ru, ru_RU, ru_UA, sh, sh_BA, sh_CS, sh_YU, sk, sk_SK, sl, sl_SI, sq, sq_AL, sr, sr_BA, sr_ME, sr_
RS, sv, sv_FI, sv_SE, th, th_TH, tr, tr_TR, uk, uk_UA, vi, vi_VN, zh, zh_CN, zh_HK, zh_HANS_SG, zh_HANT_MO, zh_MO, zh_TW]

Viết hàm riêng để đọc tiếng Việt

  • Sửa giá trị locale trong hàm convertTextToSpeech_vi() | xem file home.page.ts
  • Sừa vi_VN trong danh sách ở trên thành vi-VN
convertTextToSpeech_vi(text) {
    this.textToSpeech.speak({
        text: text,
        locale: 'vi-VN',
        rate: 1
    })
    .then(() => 
      console.log('Done')
    )
    .catch((reason: any) => 
      console.log(reason)
    );
  }

image

Link code mẫu

https://github.com/soiqualang/ionic-texttospeech-example

Leave a Reply

Your email address will not be published. Required fields are marked *