html5 localStorage缓存音乐和视频

栏目: Html5 · 发布时间: 7年前

内容简介:发表于 2018-10-24 10:29:57 by月小升原理和图片相同,只不过返回的流得头文件不同

发表于 2018-10-24 10:29:57 by月小升

缓存 音乐依靠也是浏览器得Blob对象

原理和图片相同,只不过返回的流得头文件不同

<!DOCTYPE HTML>
<html>
<body>
<figure>
 
 
<audio id="music" controls="controls"><source src="" type="audio/mpeg">Your browser does not support the audio tag.</audio>
 
 
mp3
</figure>
 
<script type="text/javascript">
 
// 获取文件
var musicStorage = localStorage.getItem("music"),
music = document.getElementById("music");
if (musicStorage) {
	 //如果已经存在则直接重用已保存的数据
	console.log("From Cache");
 	music.setAttribute("src", musicStorage);
}else{
	 // 创建XHR, BlobBuilder 和FileReader 对象
	 var xhr = new XMLHttpRequest();
 
	var fileReader = new FileReader();
 
	 xhr.open("GET", "usa.mp3", true);
 
	 xhr.responseType = 'blob';
 
	 //https://developer.mozilla.org/zh-CN/docs/Web/API/Blob    Blob可以用于存贮对象
	 //https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader/readAsDataURL
	 xhr.addEventListener("load", function () {
		 if (xhr.status === 200) {
			 var blob = this.response;
			fileReader.onload = function (evt) {
				 // 用Data URI的格式读取文件内容
			 	var result = evt.target.result;
			 	// 将图片的src指向Data URI
			 	music.setAttribute("src", result);
			 	//保存到本地存储中
				 try {
					 localStorage.setItem("music", result);
				 }
				 catch (e) {
				 console.log("Storage failed: " + e);
				 }
			 };
			 // 以Data URI的形式加载blob
			 fileReader.readAsDataURL(blob);
		 }
	 }, false);
	 // 发送异步请求
	 xhr.send();
}
 
 
</script> 
 
 
</body>
</html>

下图音乐流出来得格式

data:audio/mpeg;base64,SUQzAwAA

html5 localStorage缓存音乐和视频

首发地址:–

无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Natural Language Processing with Python

Natural Language Processing with Python

Steven Bird、Ewan Klein、Edward Loper / O'Reilly Media / 2009-7-10 / USD 44.99

This book offers a highly accessible introduction to Natural Language Processing, the field that underpins a variety of language technologies, ranging from predictive text and email filtering to autom......一起来看看 《Natural Language Processing with Python》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码