How to set HTTP-Header when streaming an Audio file?

Viewed 920

I was following the tutoriel "Building an Audio Player app with Angular and RxJS" and managed to get the audio player working.

However, in order to load the audio from my server, I need to set the Authorization header. Is there a way to do this? I am already using a HttpInterceptor for this for all other requests but it seems that the interceptor is bypassed as I load the audio file.

The code below is how the audio gets loaded and played:


private audioObj = new Audio();

// ...

private streamObservable(url: string): Observable<any> {
  return new Observable(observer => {
    // Play audio
    this.audioObj.src = url;
    this.audioObj.load();
    this.audioObj.play().then();

    const handler = (event: Event) => {
      this.updateStateEvents(event);
      observer.next(event);
    };

    this.addEvents(this.audioObj, this.audioEvents, handler);

    return () => {
      // Stop Playing
      this.audioObj.pause();
      this.audioObj.currentTime = 0;
      // remove event listeners
      this.removeEvents(this.audioObj, this.audioEvents, handler);
      // reset state
      this.resetState();
    };
  });
}
1 Answers

You can add the Authorization header to the audio URL as a URL parameter, along with a custom authentication handler on the server.

You may also (if streaming is not essential) use Angular HTTPClient to download the audio file as a Blob:

private playObservable(url: string): Observable<any> {    
  this.http.get<Blob>(url, { responseType: 'blob' })
    .pipe(
      map(blob => window.URL.createObjectURL(blob)),
      switchMap(url => {
        return new Observable(observer => {
          // Play audio
          this.audioObj.src = url;
          this.audioObj.load();
          this.audioObj.play().then();

          const handler = (event: Event) => {
            this.updateStateEvents(event);
            observer.next(event);
          };

          this.addEvents(this.audioObj, this.audioEvents, handler);

          return () => {
            // Stop Playing
            this.audioObj.pause();
            this.audioObj.currentTime = 0;
            // remove event listeners
            this.removeEvents(this.audioObj, this.audioEvents, handler);
            // reset state
            this.resetState();

            window.URL.revokeObjectURL(url)
          };

        })
      })
    )
Related