美文网首页
js 音频保存至本地

js 音频保存至本地

作者: 天天喜欢钱 | 来源:发表于2024-01-28 08:21 被阅读0次

1、读取文件流,转为base64保存

var reader = new FileReader();

      reader.onload = e => {

        let audioData = e.target.result

        window.localStorage.setItem('musicFile', audioData)

      }

      reader.readAsDataURL(file.raw)

2、在需要播放音频的文件添加元素<audio class="audioPlayer"/>

3、获取音频文件并播放

if (window.localStorage.getItem('musicFile')) {//保存了音乐

        var audioElement = document.getElementsByClassName('audioPlayer')[0];

        let file = window.localStorage.getItem('musicFile')

        audioElement.setAttribute('src', file);

        audioElement.loop = true//循环播放

        if (op == 'start') {//播放操作

            audioElement.currentTime = 0//音频设为从头开始

            audioElement.play()//开始播放

        } else {//停止播放            audioElement.pause() }

}

相关文章

网友评论

      本文标题:js 音频保存至本地

      本文链接:https://www.haomeiwen.com/subject/btzpodtx.html