class AudioPlayer { constructor(src, loop = false) { this.audio = new Audio(src); this.audio.loop = loop; this.isPlaying = false; this.hasError = false; this.logError(); } play() { if (!this.hasError) { this.audio.play(); this.isPlaying = true; } } pause() { if (!this.hasError) { this.audio.pause(); this.isPlaying = false; } } stop() { if (!this.hasError) { this.audio.pause(); this.audio.currentTime = 0; this.isPlaying = false; } } logError() { this.audio.onerror = () => { console.error("Your browser does not support audio playback."); this.hasError = true; }; } } 优化上述代码,增加在播放时指定播放次数的属性
时间: 2024-01-09 17:04:05 浏览: 146
可以在构造函数中增加一个参数 `playCount`,默认为1,表示播放次数。同时,可以在 `play()` 方法中添加逻辑,当播放次数大于0时才播放,并且每次播放完成后将播放次数减1。当播放次数为0时,自动停止播放。
优化后的代码如下:
```javascript
class AudioPlayer {
constructor(src, loop = false, playCount = 1) {
this.audio = new Audio(src);
this.audio.loop = loop;
this.isPlaying = false;
this.hasError = false;
this.playCount = playCount;
this.logError();
this.audio.addEventListener("ended", () => {
if (this.playCount > 0) {
this.playCount--;
if (this.playCount === 0) {
this.stop();
} else {
this.play();
}
}
});
}
play() {
if (!this.hasError && this.playCount > 0) {
this.audio.play();
this.isPlaying = true;
}
}
pause() {
if (!this.hasError) {
this.audio.pause();
this.isPlaying = false;
}
}
stop() {
if (!this.hasError) {
this.audio.pause();
this.audio.currentTime = 0;
this.isPlaying = false;
}
}
logError() {
this.audio.onerror = () => {
console.error("Your browser does not support audio playback.");
this.hasError = true;
};
}
}
```
使用示例:
```javascript
const player = new AudioPlayer("music.mp3", true, 3); // 播放3次
player.play(); // 开始播放
```
阅读全文