Audio - JavaScript

Audio 对象

HTML DOM Audio 对象 | 菜鸟教程

1
2
3
4
5
const music = new Audio('adf.wav');
music.play();
music.loop =true; // 将音频设为 循环播放
music.playbackRate = 2;
music.pause();qqazszdgfbgtyj

Audio API

1
2
// 补充
let data;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 获取指定音源文件的二进制数据
var xml = new XMLHttpRequest();
xml.responseType = 'arraybuffer';
xml.open('GET', 'media/piano.wav', true);
xml.onload = function() {
// 获取二进制数据并解码
ctx.decodeAudioData(
xml.response,
function(_data) {
data = _data;
},
function(err) {
// error
}
);
};
1
2
3
4
5
// 初始化AudioContext
var ctx = new AudioContext();

// AudioBufferSourceNode: 处理一次性短音的AudioNode
var bufferSource = ctx.createBufferSource();
1
2
3
4
5
6
7
8
9
10
// 保存音源
bufferSource.buffer = data;

// 与最后输出的音源连接
// AudioDestinationNode: 表示最后的输出
// 可以参考AudioContext的destination属性
bufferSource.connect(ctx.destination);

// 播放音源
bufferSource.start(0);
1
2
3
4
5
bufferSource.buffer = data;
// 设定为2倍的播放速度,频率会变为之前的2倍,音调会升高
bufferSource.playbackRate.value = 2;
bufferSource.connect(ctx.destination);
bufferSource.start(0);