【问题标题】:arraybuffor into audio srcarraybuffor 到音频 src
【发布时间】:2021-11-06 23:08:22
【问题描述】:

我从 http 响应中得到一个数组缓冲区。下面的代码只播放一次音频,但我想将音频用作音频元素的 src!

    this.toSpeechService.getAudioFile(this.text).subscribe(res => {
       const context = new AudioContext();
       let source = context.createBufferSource();
       context.decodeAudioData(res, function(buffer) {
            source.buffer = buffer;
          }, null).then(() => {
            source.connect(context.destination);
            this.audioSrc = context.destination; // doesn't fill the audio player
            source.start(0);
       });
       console.log(res)
     });
    <audio controls="controls">
      <source [src]="audioSrc" type="audio/mp3/wav" />
       Your browser does not support the audio element.
    </audio>

【问题讨论】:

  • 你能设置一个 JSFiddle 吗?

标签: javascript html5-audio audio-streaming web-audio-api


【解决方案1】:

如果您知道ArrayBuffer 中数据的 MIME 类型,则以下内容应该可以工作。

this.toSpeechService.getAudioFile(this.text).subscribe(res => {
    const blob = new Blob([ res ], { type: THE_MIME_TYPE });
    const url = URL.createObjectURL(blob);

    YOUR_AUDIO_ELEMENT.src = url;
    YOUR_AUDIO_ELEMENT.load();
});

THE_MIME_TYPE 是实际 mimeType 的占位符。 YOUR_AUDIO_ELEMENT 是对您的音频元素的引用。

一旦您不再需要对象 URL,您可以通过调用 URL.revokeObjectURL(url) 来释放内存。

【讨论】:

  • 这确实创建了一个 url (localhost:4200/afad9eca-0385-4bab-9ac2-47aaced43b2b) 但我的音频元素仍然是空的并且什么都不播放!
  • URL 与预期的一样。在这种情况下,“空”是什么意思?它允许您单击播放按钮吗?你设置了 mimeType 吗?
  • 其实你的代码只需要一个 YOUR_AUDIO_ELEMENT.load();最后,音频元素播放音频。感谢您的帮助。
  • 感谢您告诉我。我更新了答案。我的印象是没有必要。
猜你喜欢
  • 2012-06-03
  • 1970-01-01
  • 2013-04-20
  • 1970-01-01
  • 2013-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-20
相关资源
最近更新 更多