将音频保存到localStorage进行播放 [英] Saving Audio to localStorage for Playback

查看:857
本文介绍了将音频保存到localStorage进行播放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个从中拉出mp3文件的函数

I am trying to create a function in which an mp3 file is pulled from

<input type="file" id="sound" accept="audio/*"/>

并存储在Chrome中的localStorage中。 (我知道localStorage的大小有限,但我将使用的音频文件将低于2mb。)一旦存储了这个音频文件,它将被播放:

and stored in localStorage within Chrome. (I know localStorage is limited in size, but the audio files that I will be working with will be under 2mb.) Once this audio file is stored, it will be played with:

var audio = new Audio('audioFile');
audio.play();

我还是网络开发的新手,所以任何指针都会很棒!

I am still new to web development, so any pointers would be great!

注意:这不是 HTML5记录音频到文件的副本。我试图从我的HDD中取出一个预先存在的mp3文件并将其存储到localStorage中以便它可以播放。

NOTE: This is not a duplicate of HTML5 record audio to file. I am trying to take a preexisting mp3 file from my HDD and storing it into localStorage so that it can be played back.

推荐答案

这不是localStorage的意思。 localStorage只能存储字符串,只能容纳少量日期。

This is not what localStorage is meant for. localStorage can only store strings and can only accommodate a small amount of date.

如果你真的决定这样做,你需要:

If you're really determined to do this you need to:

请注意,Base64编码通常会将源素材的大小增加约33%。这是因为它可以采用任何类型的数据,包括二进制数据,并将其转换为由64字符集组成的字符串,该字符串与标准ASCII字符串兼容。

Note that Base64 encoding usually increases the size of the source material by about 33%. This is because it can take any kind of data, including binary, and converts it to a string made of a 64 character set that's compatible with standard ASCII strings.

要播放它返回,你需要相反

To play it back, you need to the opposite


  • 从localStorage检索Base64编码的字符串

  • 解码将Base64字符串转换为ArrayBuffer

  • 将ArrayBuffer加载到Audio对象中

  • 将Audio对象分配给< audio> 元素

  • retrieve the Base64 encoded string from localStorage
  • decode the Base64 string into an ArrayBuffer
  • load the ArrayBuffer into an Audio object
  • assign the Audio object to an <audio> element

还应注意,localStorage通常只有5-10MB的存储空间,具体取决于在浏览器上。这可以是在此测试,但一般来说,通过使用较低的比特率编码来保持mp3文件较小,尽可能使用单声道而不是立体声声道,如果音频只是口语而不是音乐,则降低采样率。

It should also be noted that localStorage is often only given 5-10MB of storage space, depending on the browser. This can be tested here, but generally, keep your mp3 files small by encoding them with lower bit rates, use mono instead of stereo channels where possible, and reduce sample rate if the audio is just spoken words and not music.

这篇关于将音频保存到localStorage进行播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆