speech recognition does not return good the value on time ionic 5

北慕城南 提交于 2020-03-25 18:45:17

问题


I have a problem with this ionic plugin, I do everything right, but when you bring me the data, it does so after a subsequent action, such as pressing the button again or simply pressing some other element. I leave my code in case someone can help me.

Below is my HTML code:



<ion-header class="ion-no-border">
    <ion-grid fixed>
        <ion-row>
            <ion-col size="10">
                <ion-searchbar cancelable="true" [(ngModel)]="textoBuscar" (ionInput)="getItems($event)" debounce=1 (enter)="getItems($event)" search-icon="search-outline" placeholder="Buscar..."></ion-searchbar>
            </ion-col>
            <ion-col size="2">
                <ion-col>
                    <ion-buttons expand="full">
                        <ion-button full (click)="start()"></ion-button>
                        <ion-icon name="mic-outline"></ion-icon>
                    </ion-buttons>
                </ion-col>
            </ion-col>
        </ion-row>
    </ion-grid>

</ion-header>
<ion-content [fullscreen]="true">
    <ion-card *ngFor="let producto of arrayProductos">
        <ion-card-header>
            <ion-img [src]="producto.foto"></ion-img>
            <ion-card-header>
                <ion-card-subtitle>{{producto.nombre}}</ion-card-subtitle>
                <ion-card-title>{{producto.nombre}}</ion-card-title>
            </ion-card-header>
            <ion-card-content>Cantidad: {{producto.cantidad}}
            </ion-card-content>
            <ion-card-content>Precio: {{producto.precio}}
            </ion-card-content>
        </ion-card-header>
    </ion-card>
</ion-content>

Below is my Typescript Code:



import { Component} from '@angular/core';
import { SpeechRecognition } from '@ionic-native/speech-recognition/ngx';

@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss']
})
export class Tab1Page {
  message: string;
  textoBuscar = '';
arrayProductos = [];
constructor(private speechRecognition: SpeechRecognition) {

this.getArrayFotos();
this.startRecognition();
}


ionViewDidLoad() {
  this.getPermission();
}

 // Esta función es la encargada de activar el reconocimiento de voz
 startListening() {
  const options = {
    language: 'es-ES', // fijamos el lenguage
    matches: 1, // Nos devuelve la primera opción de lo que ha escuchado
    // si ponemos otra cantidad, nos dará una variante de la palabra/frase que le hemos dicho
  };
  this.speechRecognition.startListening(options).subscribe(matches => {
    this.message = matches[0]; // Guarda la primera frase que ha interpretado en nuestra variable
    console.log(this.message);
  });
}
getPermission() {
  // comprueba que la aplicación tiene permiso, de no ser así nos la pide
  this.speechRecognition.hasPermission().
    then((hasPermission: boolean) => {
      if (!hasPermission) {
        this.speechRecognition.requestPermission();
      }
    });
}



getArrayFotos() {
this.arrayProductos = [
    {
    nombre:  'Polera polo xl',
    precio: 3000,
    cantidad: 20,
    foto: 'https://www.brooksbrothers.cl/pub/media/catalog/product/cache/image/e9c3970ab036de70892d86c6d221abfe/b/1/b100076744_bb42_1.jpg'
    },
    {
    nombre: 'Polera adidas',
    precio: 2000,
    cantidad: 10,
    // tslint:disable-next-line:max-line-length
    foto: 'https://assets.adidas.com/images/w_840,h_840,f_auto,q_auto:sensitive,fl_lossy/68ad41ef8bb84fe1b96aaac001746ff7_9366/Polera_Polo_Designed_2_Move_3_Franjas_Blanco_FL0322_01_laydown.jpg'
}];

}

startListen() {
  this.speechRecognition.startListening()
    .subscribe(matches => {
      const matchof: string = matches[0].toString();
      this.textoBuscar = matchof;
      this.arrayProductos = this.arrayProductos.filter((producto) => {
        return producto.nombre.toLowerCase().indexOf(this.textoBuscar.toLowerCase()) > -1;
      });
    });
}


startRecognition() {

this.speechRecognition.hasPermission()
  .then((hasPermission: boolean)  => {
  if (hasPermission) {
    this.speechRecognition.requestPermission()
  .then(
    () => console.log('Tienes permiso'),
    () => console.log('No tienes permiso del microfono'));
   }});
}


// buscar(event?, buscar: string = '') {

//   if (buscar.length > 0) {
//     this.textoBuscar = buscar;
//   }
//   if (event !== undefined) {
//     this.textoBuscar = event.detail.value;

//   }
//  }

 getItems(ev) {
  const val = ev.target.value;
  if (val && val.trim() !== '') {
    this.arrayProductos = this.arrayProductos.filter((producto) => {
      return producto.nombre.toLowerCase().indexOf(this.textoBuscar.toLowerCase()) > -1;
    });
} else {
this.getArrayFotos();
}}



active() {
  console.log('active');
}

stop() {
  this.speechRecognition.stopListening();
  console.log('Finished recording');
}

  getPermisson() {
    // Check feature available
    this.speechRecognition.hasPermission()
      .then((hasPermission: boolean) => {
        if (!hasPermission) {
            this.speechRecognition.requestPermission()
              .then(
                () => console.log('Granted'),
                () => console.log('Denied')
              );
          }
        });
      }

      start() {
        const options = {
          language: 'es-ES'
        };
        this.speechRecognition.startListening(options)
        .subscribe(
          (matches: Array<string>) => {
            console.log(matches);
            this.textoBuscar = matches[0].toString();
            this.arrayProductos = this.arrayProductos.filter((producto) => {
              return producto.nombre.toLowerCase().indexOf(this.textoBuscar.toLowerCase()) > -1;
            });
          },
          (onerror) =>   this.stop(),
        ); }
}


回答1:


I am unable to enable speech recognition to test your code. But if speech recognition is working, then you must update the textoBuscar variable with recognized value and use ionChange event in searchbar instead of ionInput. ionInput is on keyboard key press. For debugging after speach regonition happens, console the value of texttoBuscar and update the getItems() method as below:

getItems(ev) {
    this.textoBuscar = this.textoBuscar.trim().toLowerCase();

    if(!this.textoBuscar) {
       this.getArrayFotos();
       return;
    }

    this.arrayProductos = this.arrayProductos.filter(producto => producto.nombre.toLowerCase().indexOf(this.textoBuscar) > -1);
}

html

 <ion-searchbar cancelable="true" [(ngModel)]="textoBuscar" (ionChange)="getItems($event)" debounce=1 (enter)="getItems($event)"
      search-icon="search-outline" placeholder="Buscar..."></ion-searchbar>


来源:https://stackoverflow.com/questions/60432540/speech-recognition-does-not-return-good-the-value-on-time-ionic-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!