I am currently developing a web application using Angular4 that will include the feature of playing audio files. Unfortunately, I am facing an issue where I do not have control over the server serving the media files, and therefore cannot make any modifications to the server settings.
When I directly create an audio element and play it, the audio playback works perfectly:
var audio = new Audio();
audio.src = item.url; // 'item' is an object containing the URL and title
audio.load();
audio.play();
However, when I utilize a player-class to manage the playback functionality, I encounter a CORS error due to inadequate headers being set for the mp3 items:
@Injectable
export class Player {
audio: any;
constructor(private zone: NgZone){
this.initialize();
}
initialize(){
if (!this.audio) {
this.audio = new Audio();
this.audio.autoplay.false;
this.audio.preload = 'auto';
this.audio.autobuffer = true;
this.audio.crossOrigin = "anonymous";
}
}
setUrl(url: string) {
this.initialize();
this.audio.pause();
this.audio.src = url;
this.audio.load();
}
play() {
this.audio.play();
}
pause() {
this.audio.pause();
}
}
The error message received upon attempting to play the audio indicates that the CORS policy restricts the playback of the item:
Uncaught (in promise) DOMException: Failed to load because no supported source was found.
Is there a possible workaround for this issue? And why does the direct calling of the audio element in the controller result in successful playback?