0

I am aware of the NativeAudio solution, but I was wondering if it's possible to do this completely through Angular.

So far I have something but it's not really working:

import { Injectable } from '@angular/core'

@Injectable({
  providedIn: 'root',
})
export class AudioService {

  audio: HTMLAudioElement

  constructor() {
    this.audio = new Audio()
  }

  playScan = async () => {
    this.audio.src = './sound4_selfservice_scan_item.wav'
    this.audio.load()
    await this.playAudio()
  }

  playIssue = async () => {
    this.audio.src = './sound3_checkin_denied.wav'
    await this.playAudio()
  }

  playAudio = () => this.audio.play()
}

and in my component:

@Component({
  selector: 'scan-retail-items',
  template: `
      <div class="app-container scan-item-component {{mode}} {{scanClass}}">
          <main-navigation [member]="handOffMember"
                           (onBackPressed)="onBackPressed($event)"></main-navigation>
          <div class="main-container -expanded">
                              <ion-button
                                      color="secondary"
                                      *virtualItem="let item"
                                      (click)="clickTestButton(item.upc)">{{item.name}}
                              </ion-button>
                          </ion-virtual-scroll>
                      </ion-content>
                  </div>
              </main-body>
              <status-icon mode={{mode}}></status-icon>
          </div>
      </div>
  `,
  styleUrls: ['./scan_retail_items.component.scss'],
})

export class ScanRetailItemsComponent implements OnInit, OnDestroy {


  constructor(private audio: AudioService) {
  }


  ngOnInit(): void {
  }

  clickTestButton = async (upc: string) => {
    console.log('Test Product Scan: ' + upc)
    this.addItemByUPC({ scanData: upc })
    await this.audio.playScan()
  }

Clicking on the button calls clickTestButton and it should theoretically play the sound, but it doesn't seem like it's doing it. Is there anything I'm doing wrong until I move on to Native Audio?

nyphur
  • 2,404
  • 2
  • 24
  • 48

1 Answers1

0

If you want to play audio using an HTML element you should first add it to the body of your html. If you want a full typescript solution, you can follow the most voted answer on this other stackoverflow question: Play sound in Angular 4

A very easy way to test this. Create an empty index.html file in a folder. Put a WAV file named audio.wav in the same folder. Now open index.html in the browser. Then open DevTools and run this script:

let audio = new Audio();
audio.src = "./audio.wav";
audio.load();
audio.play();

your WAV file should now be correctly reproduced