HTML5 网页使用 Base64 音频或视频源


HTML5 网页使用 Base64 音频或视频源

视频转 Base64,使用 FileReader 实现

FileReader 对象允许 Web 应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容,使用 FileBlob 对象指定要读取的文件或数据。

其中 File 对象可以是来自用户在一个<input>元素上选择文件后返回的FileList对象,也可以来自拖放操作生成的 DataTransfer对象,还可以是来自在一个HTMLCanvasElement上执行mozGetAsFile()方法后返回结果。

重要提示: FileReader 仅用于以安全的方式从用户(远程)系统读取文件内容 它不能用于从文件系统中按路径名简单地读取文件。 要在 JavaScript 中按路径名读取文件,应使用标准 Ajax 解决方案进行服务器端文件读取,如果读取跨域,则使用 CORS 权限。

属性

FileReader.readyState 只读

表示FileReader状态的数字。取值如下:

常量名 描述
EMPTY 0 还没有加载任何数据.
LOADING 1 数据正在被加载.
DONE 2 已完成全部的读取请求.

FileReader.result 只读

文件的内容。该属性仅在读取操作完成后才有效,数据的格式取决于使用哪个方法来启动读取操作。

事件

FileReader.onload

处理load (en-US)事件。该事件在读取操作完成时触发。

因为 FileReader 继承自EventTarget,所以所有这些事件也可以通过addEventListener方法使用。

方法

Data URLs

Data URLs 由四个部分组成:前缀(data:)、指示数据类型的 MIME 类型、如果非文本则为可选的base64标记、数据本身:

data:[<mediatype>][;base64],<data>

mediatype 是个 MIME 类型的字符串,例如 “image/jpeg“ 表示 JPEG 图像文件。如果被省略,则默认值为 text/plain;charset=US-ASCII

如果数据是文本类型,你可以直接将文本嵌入 (根据文档类型,使用合适的实体字符或转义字符)。如果是二进制数据,你可以将数据进行 base64 编码之后再进行嵌入。

A Data URI takes the format: 格式

data:[<MIME-type
  >][;charset=<encoding>][;base64],<data></data></encoding
></MIME-type>

The MIME-type specifies what type of data the URI contains. So if you wanted to provide a data URI for an image you would specify it as follows:

<MIME-type> 指定内容格式

<img
  src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg=="
  alt="Red dot"
/>

The MIME type used here is image/png indicating that the encoded data is a PNG image.

Audio

Similarily, if you wanted to encode an Ogg audio file, you would use the MIME type audio/ogg as follows:

<audio controls src="data:audio/ogg;base64,T2dnUwACAAAAAAAAAAA+..........+fm5nB6slBlZ3Fcha363d5ut7u3ni1rLoPf728l3KcK" />

If you want to specify an MP3 file you would simply set the MIME type to audio/mp3 and provide the encoded MP3 audio data string.

See an example of a data URI audio source.

Video

Providing a data URI for an encoded video is just the same, providing the correct MIME type for the correct encoded data, and of course they can be used in conjunction with the source element:

<video controls>
  <source type="video/webm" src="data:video/webm;base64,GkXfowEAAAAAAAAfQoaBAUL3gQFC8......jVOrhB9DtnVTrIMQTPc=" />
  <source type="video/mp4" src="data:video/mp4;base64,AAAAHGZ0eXBtcDQyAAAAAG1wNDJpc29....../l/L+X8v5AAAAMgfDg==" />
</video>

See an example of a data URI video source.

Encoding in base64

Of course the code examples provided above don’t display the full data URI for any of the audio and video files as they would fill the entire page! To encode the data I simply used PHP‘s base64_encode function as follows:

function getEncodedVideoString($type, $file) {
   return 'data:video/' . $type . ';base64,' . base64_encode(file_get_contents($file));
}

Which was used by the HTML:

<video controls>
  <source type="video/webm" src="<?php echo getEncodedVideoString('webm', 'parrots-small.webm'); ?>" />
  <source type="video/mp4" src="<?php echo getEncodedVideoString('mp4', 'parrots-small.mp4');?>" />
</video>

Of course you can use whatever you like to encode the files, this is just an example. And while you may not want nor need to base64 encode your audio and video files (these reasons on why you might base64 encode images might be just as relevant), it’s still good to know that you can should the need arise.

实现代码

<div class="base64"></div>
<script>
  function genAudio(base64Audio) {
    let audio = document.createElement('audio');
    audio.id = 'audio1';
    audio.loop = 'true';
    audio.autoplay = 'true';
    audio.controls = true;
    audio.src = base64Audio;
    audio.volume = 0.5; // 最小值0.5
    return audio;
  }

  // 新键文件输入框元素
  const input = document.createElement('input');
  input.type = 'file';

  // 文件输入框插入位置
  document.querySelector('.base64').append(input);

  input.onchange = function () {
    const files = input.files; // e.target.files; // FileList
    const reader = new FileReader();
    reader.readAsDataURL(files[0]); // 转Base64

    reader.onload = function () {
      console.log('base64 result:', reader.result);
      const audio = genAudio(reader.result);
      // 音频插入位置
      document.querySelector('.base64').append(audio);
    };
  };
</script>

文章作者: iKnow
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 iKnow !
评论
 上一篇
JavaScript Promise 并发控制下载文件的实现 JavaScript Promise 并发控制下载文件的实现
Promise 并发下载Promise.then.then 的第一个参数是一个函数,该函数将在 promise resolved 后运行并接收结果。 .then 的第二个参数也是一个函数,该函数将在 promise rejected 后运行
2021-07-29
下一篇 
使用 jsDelivr 加速 Github 资源,加快博客打开速度 使用 jsDelivr 加速 Github 资源,加快博客打开速度
GitHub CDN 使用说明在 GitHub 创建公开项目即可使用 jsDelivr 访问: We recommend using npm for projects that support it for better UX - npm
2021-07-21
  目录