市面上实现音频播放器的库有很多,比如wavesurfer.js、howler.js等等,但是都不支持大音频文件处理,100多M的文件就有可能导致程序崩溃。总之和我目前的需求不太符合,所以打算自己实现一个音频播放器,这样不管什么需求 在技术上都可控。下面我们简单介绍下
wavesurferJs
、和howlerJs
的实现,然后再讲解如何利用audio API实现自定义语音播放器。
具体资源github下载
wavesurferJs
一开始选择wavesurferJs
主要是因为它的音频图功能。
效果如下:
是不是很漂亮 hh
下面是实现步骤:
- 初始化
this.playWavesurfer = WaveSurfer.create({
container: '#waveform2',
mediaType: 'audio',
height: 43,
scrollParent: false,
hideScrollbar: true,
waveColor: '#ed6c00',
interact: true,
progressColor: '#dd5e98',
cursorColor: '#ddd5e9',
interact: true,
cursorWidth: 1,
barHeight: 1,
barWidth: 1,
plugins: [
WaveSurfer.microphone.create()
]
});
- 动态加载音频地址
this.playWavesurfer.load(this.audioUrl);
- 设置加载loading和完毕后计算音频总时长
this.playWavesurfer.on('loading', (percent, xhr) => {
this.audioLoadPercent = percent - 1;
})
this.playWavesurfer.on('ready', () => {
this.audioLoading = false;
const duration = this.playWavesurfer.getDuration();
this.duration = this.formatTime(duration);
this.currentTime = this.formatTime(0);
})
- 播放中计算时长
this.playWavesurfer.on('audioprocess', function () {
const duration = that.playWavesurfer.getDuration();
const currentTime = that.playWavesurfer.getCurrentTime();
that.currentTime = that.formatTime(currentTime);
that.duration = that.formatTime(duration);
if (that.currentTime === that.duration) {
that.audioPlayingFlag = false;
}
});
- 播放、暂停
this.playWavesurfer.playPause.bind(this.playWavesurfer)();
- 快进、快退
this.playWavesurfer.skip(15);
//this.playWavesurfer.skip(-15);
- 倍数播放
this.playWavesurfer.setPlaybackRate(value, true);
这样基本功能大概实现。
利用howlerJs实现
- 初始化、动态加载音频路径
this.howler = new Howl({
src: [this.audioUrl]
});
- 加载完毕计算音频总时长
this.howler.on('load', () => {
this.audioLoading = false;
const duration = this.howler.duration();
this.duration = this.formatTime(duration);
this.currentTime = this.formatTime(0);
});
- 播放中获取当前时间
this.currentTime = this.formatTime(this.howler.seek());
- 播放完毕
this.howler.on('end', () => {
this.audioPlayingFlag = false;
this.siriWave2.stop();
this.currentTime = "00:00:00";
this.progressPercent = 0;
cancelAnimationFrame(this.playTimer);
})
- 快进、快退
this.howler.seek(this.howler.seek() + 15);
//this.howler.seek(this.howler.seek() - 15);
- 设置倍数播放
this.howler.rate(value);
- 播放、暂停
this.howler.play();
// this.howler.pause();
- 手动定位播放时长
<div id="waveform2" ref="waveform2" @click="changProgress">
<div class="bar" v-if="!audioLoading&&!audioPlayingFlag"></div>
<div class="progress" :style="{width: `${progressPercent}`}"></div>
</div>
changProgress(e) {
if (this.howler.playing()) {
this.howler.seek((e.offsetX / this.$refs['waveform2'].offsetWidth)*this.howler.duration());
}
},
这样基本功能大概实现。
利用audio API实现播放器
效果图:
动画库 暂时用的 siriwave.js
先定义audio标签隐藏,可以js里面动态生成
<audio :src="audioUrl" style="display: none;" controls ref="audio"></audio>
this.audio = this.$refs['audio'];
- 获取音频url后 动态加载 需要load一下
this.audio.load();
- 音频加载完毕
this.audio.addEventListener("canplaythrough", () => {
this.audioLoading = false;
console.log('music ready');
}, false);
- 监听可以播放后 计算音频时长
this.audio.addEventListener("canplay", this.showTime, false);
showTime() {
if (!isNaN(this.audio.duration)) {
this.duration = this.formatTime(this.audio.duration);
this.currentTime = this.formatTime(this.audio.currentTime);
}
},
- 播放中 时间改变计算当前 时间
this.audio.addEventListener("timeupdate", this.showTime, true);
- 监听播放事件
this.audio.addEventListener('play', () => {
this.audioPlaying();
}, false);
- 播放完毕
this.audio.addEventListener('ended', () => {
this.audioPlayingFlag = false;
this.siriWave2.stop();
this.currentTime = "00:00:00";
this.progressPercent = 0;
cancelAnimationFrame(this.playTimer);
}, false)
- 前进、后退
this.audio.currentTime += 15;
// this.audio.currentTime -= 15;
- 设置播放倍数
this.audio.playbackRate = value;
- 播放、暂停
this.audio.play();
// this.audio.pause();
- 音频定位
<div id="waveform2" ref="waveform2" @click="changProgress">
<div class="bar" v-if="!audioLoading&&!audioPlayingFlag"></div>
<div class="progress" :style="{width: `${progressPercent}`}"></div>
</div>
计算 定位时长
changProgress(e) {
// if (this.audioPlayingFlag) {
this.audio.currentTime = (e.offsetX / this.$refs['waveform2'].offsetWidth)*this.audio.duration;
this.progressPercent = ((this.audio.currentTime/this.audio.duration) * 100) + '%';
// }
},
- siri动画实现
this.siriWave = new SiriWave({
container: that.$refs['waveform'],
height: 43,
cover: true,
color: '#ed6c00',
speed: 0.03,
amplitude: 1,
frequency: 6
});
开启动画、停止动画
this.siriWave.start();
// this.siriWave.stop();
这样基本功能大概实现。 即使加载再大音频文件也不会卡。
踩坑
这里遇到一个大坑就是 audio自带,音频播放定位功能,在外面浏览器和vscode主体代码里面都可以定位,偏偏我在vscode插件里面不可以定位,会自动归0。翻遍了文档在MDN上找到这样一段描述:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Configuring_servers_for_Ogg_media#Handle_HTTP_1.1_byte_range_requests_correctly
Handle HTTP 1.1 byte range requests correctly
In order to support seeking and playing back regions of the media that aren’t yet downloaded, Gecko uses HTTP 1.1 byte-range requests to retrieve the media from the seek target position. In addition, Gecko uses byte-range requests to seek to the end of the media (assuming you serve the Content-Length
header) in order to determine the duration of the media.
Your server should accept the Accept-Ranges
: bytes HTTP header if it can accept byte-range requests. It must return 206: Partial content to all byte range requests; otherwise, browsers can’t be sure you actually support byte range requests.
Your server must also return 206: Partial Content for the request Range: bytes=0- as well.
经验证是和response header
有关的。我通过对MP3资源set不同的response header
来验证,结果如下(貌似segmentfault不支持markdown的表格,所以下面排版有点乱。):
ie
Content-Type
必须,当我设为audio/mpeg时才能播放,设为application/octet-stream不能。
Content-Length
必须。和Accept-Ranges无关。
chrome
Content-Type
无关,设为application/octet-stream
可以播放。
Content-Length
,Accept-Ranges
必须都有才可更改 currentTime。
也就是说ie需要response header 有正确的Content-Type
,Content-Length
。
chrome需要头部有Content-Length
和Accept-Ranges
。
然后我想到 vscode插件系统使用了 Service Worker
const headers = {
'Content-Type': entry.mime,
'Content-Length': entry.data.byteLength.toString(),
'Access-Control-Allow-Origin': '*',
};
果然 没有添加 Accept-Ranges字段
const headers = {
'Content-Type': entry.mime,
'Content-Length': entry.data.byteLength.toString(),
'Access-Control-Allow-Origin': '*',
};
/**
* @author lichangwei
* @description 音频额外处理 否则无法调节进度
* https://developer.mozilla.org/en-US/docs/Web/HTTP/Configuring_servers_for_Ogg_media#Handle_HTTP_1.1_byte_range_requests_correctly
*/
if (entry.mime === 'audio/mpeg') {
headers['Accept-Ranges'] = 'bytes';
}
添加后就可以使用了。
后续
看了一下印象笔记的语音笔记实现。
印象笔记是如何避免大文件处理的呢
- 首先录音过程中绘制的是真的音频线
- 录音结束后是用假的音频线替代的
其实录制过程中实时处理音频数据还好,不至于导致浏览器崩溃,录制后生成的音频文件处理数据量太大了,内存直接飙升2-3G,所以会导致程序崩溃
后续实现音频图