简体   繁体   English

如何在我的 chrome 扩展程序中保存 state 的音频 blob?

[英]How to save state of audio blob in my chrome extension?

I have the following popup.js file in which I capture audio from a tab and store it in a blob and then set my audio tag's src URL to it.我有以下 popup.js 文件,我在其中从选项卡捕获音频并将其存储在 blob 中,然后将我的音频标签的 src URL 设置为它。 I would like to store this blob in chrome's local storage so that the audio data remains even after closing the extension's popup.html window. How do I go about doing this?我想将此 blob 存储在 chrome 的本地存储中,以便即使在关闭扩展程序的弹出窗口后音频数据仍然存在。html window。我 go 如何执行此操作? I tried to serialize the blob to JSON using ArrayBuffer but it seemed to not be the correct method.我尝试使用 ArrayBuffer 将 blob 序列化为 JSON 但它似乎不是正确的方法。 If there is a better way please let me know.如果有更好的方法请告诉我。 Thanks.谢谢。

function captureTabAudio() {
  chrome.tabCapture.capture({ audio: true, video: false }, (stream) => {

    context = new AudioContext();
    const chunks = [];
    if (context.state === 'suspended') {
      context.resume();
    }
    var newStream = context.createMediaStreamSource(stream);
    newStream.connect(context.destination);

    const recorder = new MediaRecorder(stream);
    recorder.start();

    setTimeout(() => recorder.stop(), 10000);

    recorder.ondataavailable = (e) => {
      chunks.push(e.data);
    };

    recorder.onstop = (e) => {
      const blob = new Blob(chunks, { type: "audio/ogg; codecs=opus" });
      document.querySelector("audio").src =
        URL.createObjectURL(blob);
    };
  })
}

I assume that when you say "Chrome's local storage" you mean the web's localStorage API. If so, this won't work because, "The keys and the values stored with localStorage are always in the UTF-16 string format, which uses two bytes per character" ( MDN ).我假设当你说“Chrome 的本地存储”时,你指的是网络的localStorage API。如果是这样,这将不起作用,因为“使用 localStorage 存储的键和值始终采用 UTF-16 字符串格式,它使用两个每个字符的字节数”( MDN )。 If you meant the extension platform'sStorage API , you'll have a similar problem because it only supports JSON-serializable values.如果你指的是扩展平台的Storage API ,你会遇到类似的问题,因为它只支持 JSON 可序列化的值。 While you could potentially convert the ArrayBuffer into a Base64 string, I wouldn't recommend it as you're more likely to run into storage limits.虽然您可能会将 ArrayBuffer 转换为 Base64 字符串,但我不建议这样做,因为您更有可能遇到存储限制。

For storing binary data locally, currently your best bet is to use IndexedDB.对于在本地存储二进制数据,目前最好的选择是使用 IndexedDB。 Since this API supports the structured clone algorithm , it supports a much broader set of types including ArrayBuffer.由于这个 API 支持结构化克隆算法,它支持更广泛的类型集,包括 ArrayBuffer。 A similar question was asked here: Saving ArrayBuffer in IndexedDB .这里提出了一个类似的问题: Saving ArrayBuffer in IndexedDB

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM