Play audio in angular

-1

Hello friends, I want to reproduce in the html an audio that you find in a music folder that is in the same project.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-audio',
  templateUrl: './audio.component.html',
  styles: []
})
export class AudioComponent implements OnInit {

  audio = "./../../../musica/Hola.mp3";

  constructor() { }

  ngOnInit() {
  }

}

This is the music folder that contains the music

    
asked by Chris Alexis 27.11.2018 в 21:36
source

1 answer

1

First of all, you are in a browser so your server must serve the audio file as well so that it is available. That it is in a folder on your PC does not mean anything because when you move it to the internet your application the audio file will remain in your folder and will not work.

Inside the folder src there is another folder assets where the photos and other resources are put, copy your file there and then you just have to add a <audio> tag to your html

<audio controls src='assets/Hola.mp3' type="audio/mp3">
    Your browser does not support the <code>audio</code> element.
</audio>

To do it by code you have to write this in your component

export class AudioComponent {
    reproducir() {
        const audio = new Audio('assets/Hola.mp3');
        audio.play();
    }
}

In the template, some button must have something like this (click)="reproducir()"

When you build your audio file it will also be included when it is within assets and it will work both locally and on the internet.

    
answered by 27.11.2018 в 22:39