# h5中原生js选择本地音乐播放

先放一个原生js的,可以选择本地电脑的音乐,然后进行播放

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>audioplay</title>
</head>
<body>
    <input type="file" id="file" accept="audio/x-wav,audio/mpeg" />

</body>
<script>
var context = null;

document.getElementById('file').addEventListener('change', function(e) {
    var read = new FileReader();

    context = new (window.AudioContext || window.webkitAudioContext)();

    read.onload = function() {
        // 将arrayBuffer转成audioBuffer
        context.decodeAudioData(this.result, function(buffer) {
            playSound(buffer);
        }, function() {
            console.log('error');
        });
    };
    console.log(this.files[0]);
    // 利用filereader将file转成arraybuffer格式
    read.readAsArrayBuffer(this.files[0]);
});
// 播放音频
function playSound(buffer) {
    var source = context.createBufferSource();

    // 设置数据
    source.buffer = buffer;
    source.loop = true; //循环播放
    // connect到扬声器
    source.connect(context.destination);
    source.start();
}
</script>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45