Распознавание речи не возвращает хорошее значение по времени IONI c 5 - PullRequest
0 голосов
/ 27 февраля 2020

У меня проблема с этим плагином ioni c, я все делаю правильно, но когда вы приносите мне данные, это происходит после следующего действия, например, повторного нажатия кнопки или простого нажатия какого-либо другого элемента. Я оставляю свой код на случай, если кто-то может мне помочь.

Ниже мой HTML код:

</p>

<pre><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>

Ниже мой машинописный код:

</p>

<pre><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 Ответ

0 голосов
/ 28 февраля 2020

Я не могу включить распознавание речи для проверки вашего кода. Но если распознавание речи работает, вы должны обновить переменную textoBuscar с распознанным значением и использовать событие ionChange в строке поиска вместо ionInput. ionInput находится на нажатии клавиши клавиатуры. Для отладки после того, как произойдет речевое повторение, утешите значение texttoBuscar и обновите метод getItems (), как показано ниже:

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>
...