【问题标题】:Return a blob from an observable从 observable 返回一个 blob
【发布时间】:2021-11-07 16:26:28
【问题描述】:

这个函数应该从 localStorage 读取一个值或从 API 获取它并以两种方式返回一个 blob。

这是服务功能:

      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))
      }

这是我的组件函数:

  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();
    });
}

此代码在应从 API 获取日期但何时从本地存储读取时运行良好,console.log(res) 什么也不显示!

【问题讨论】:

  • 您可能希望首先将您的 blob 数据转换为本地存储中的数据 uri,您可能需要检查这一点,link
  • 试过了,没有任何区别! @NoxinDVictus

标签: angular observable blob


【解决方案1】:

可能你必须在将 blobOject 写入本地存储之前对其进行序列化,并在从本地存储中读取它后进行反序列化:

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

序列化:(到字符串): JSON.stringify();

反序列化:
JSON.parse();

例如:在您的代码中:

.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'});
           });
        }

【讨论】:

  • 我绝对应该以某种方式解码 blob 以便将其保存在 localStorage 中,但 JSON.stringify( ) 不是诀窍!
猜你喜欢
  • 2020-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-21
  • 2016-11-27
相关资源
最近更新 更多