网页播放音频封装
时间: 2023-07-04 11:23:24 浏览: 44
常见的网页音频播放方式有两种:使用HTML5的audio标签和使用JavaScript控制音频播放。
使用HTML5的audio标签的代码如下:
```
<audio src="audio.mp3" controls></audio>
```
其中,`src`属性指定音频文件的路径,`controls`属性表示显示音频控制条。
使用JavaScript控制音频播放的代码如下:
```
var audio = new Audio('audio.mp3');
audio.play();
```
其中,`Audio`对象表示一个音频,`play()`方法表示播放音频。
为了更好地封装音频播放,可以定义一个`AudioPlayer`对象,它提供了`play()`、`pause()`、`stop()`等方法,以及`onplay`、`onpause`、`onstop`等事件。
```
function AudioPlayer(src) {
this.audio = new Audio(src);
this.audio.addEventListener('ended', function() {
this.dispatchEvent(new Event('stop'));
}.bind(this));
}
AudioPlayer.prototype.play = function() {
this.audio.play();
this.dispatchEvent(new Event('play'));
};
AudioPlayer.prototype.pause = function() {
this.audio.pause();
this.dispatchEvent(new Event('pause'));
};
AudioPlayer.prototype.stop = function() {
this.audio.pause();
this.audio.currentTime = 0;
this.dispatchEvent(new Event('stop'));
};
AudioPlayer.prototype.addEventListener = function(type, listener) {
this.audio.addEventListener(type, listener);
};
AudioPlayer.prototype.dispatchEvent = function(event) {
this.audio.dispatchEvent(event);
};
```
使用`AudioPlayer`对象的代码如下:
```
var player = new AudioPlayer('audio.mp3');
player.addEventListener('play', function() {
console.log('play');
});
player.addEventListener('pause', function() {
console.log('pause');
});
player.addEventListener('stop', function() {
console.log('stop');
});
player.play();
player.pause();
player.stop();
```