-
-
Notifications
You must be signed in to change notification settings - Fork 263
/
audio.html
79 lines (72 loc) · 2.31 KB
/
audio.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<!--
* @Author: chenzhongsheng
* @Date: 2023-03-18 16:52:44
* @Description: Coding something
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext;
try {
var context = new window.AudioContext();;
var source = null;
var audioBuffer = null;
function stopSound() {
if (source) {
source.stop(0); //立即停止
}
}
function playSound() {
source = context.createBufferSource();
source.playbackRate.value = 1;
source.buffer = audioBuffer;
// source.loop = true; //循环播放
const gain = context.createGain();
gain.gain.value = 1;
source.connect(gain);
gain.connect(context.destination);
// source.connect(context.destination);
source.start(0); //立即播放
}
function initSound(arrayBuffer) {
context.decodeAudioData(arrayBuffer, function(buffer) { //解码成功时的回调函数
audioBuffer = buffer;
playSound();
}, function(e) { //解码出错时的回调函数
console.log('Error decoding file', e);
});
}
function loadAudioFile(url) {
var xhr = new XMLHttpRequest(); //通过XHR下载音频文件
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = () => {
if (xhr.status === 200) {
if (xhr.readyState === 4) {
console.log('response decodeArrayBuffer', xhr.response);
// decodeArrayBuffer(xhr.response, resolve);
initSound(xhr.response);
}
} else {
resolve(null);
}
};
// xhr.onload = function(e) { //下载完成
// initSound(this.response);
// };
xhr.send();
}
loadAudioFile('https://unpkg.com/[email protected]/voice/hao3.mp3');
} catch (e) {
console.log('!Your browser does not support AudioContext');
}
</script>
</body>
</html>