1

This function is supposed to read a value from localStorage or get it from API and return a blob in both ways.

This is the service function:

      getAudioFile (text: string): Observable<Blob> {
        if (localStorage.getItem(text)) {
           return new Observable(() => {
             return new Blob([localStorage.getItem(text)], {type: 'audio/wav'});
           });
        }
        return this.http.post(this.cors + this.apiUrl, {}, {
            headers: {
              'Content-Type' : 'application/json',
              'Accept' : 'audio/wav',
            },
            params: {
              voice: 'en-US_AllisonV3Voice',
              text : text
            },
            responseType: 'blob'
          }).pipe(map(res => {
            res.text().then((strBlob => {
              localStorage.setItem(text, strBlob);
            }))
            return res;
         }),catchError(this.handleError))
      }

And this is my component function:

  toSpeech() {
    this.toSpeechService.getAudioFile(this.text).subscribe(res => {
      console.log(res)          // show nothing when blob is from localstorage
      const EL_audio = document.querySelector("audio");
      EL_audio.src = URL.createObjectURL(res);
      EL_audio.load();
    });
}

This code works fine when the date should be fetched from API but when is it read from localstorage, console.log(res) shows nothing!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Qiimiia
  • 510
  • 6
  • 16
  • You might want to covert your blob data first to as a data uri in local storage, You might want to check this, [link](https://stackoverflow.com/questions/21008732/javascript-save-blob-to-localstorage) – Noxin D Victus Sep 11 '21 at 16:20
  • Tried it and no difference was made! @NoxinDVictus – Qiimiia Sep 12 '21 at 03:51

1 Answers1

0

Probably you have to serialize the blobOject before write it into the localstorage, and deserialize once read it from localstorage:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Serialize: (to string): JSON.stringify();

Deserialize :
JSON.parse();

e.g: In your code:

.pipe(map(res => {
            res.text().then((mYBlob => {
               const strBlob:string = JSON.stringify( mYBlob );
               localStorage.setItem('text', strBlob);
            }))
 return res;
         }),catchError(this.handleError))
´´´
  if (localStorage.getItem(text)) {
           return new Observable(() => {

           const blobString= localStorage.getItem('text');
           const myBlob= JSON.parse( blobString );

             return new Blob([ myBlob ], {type: 'audio/wav'});
           });
        }
  • I defiantly should somehow decode blob in order to save it in localStorage, but `JSON.stringify( )` is not the trick! – Qiimiia Sep 12 '21 at 03:50