-
Notifications
You must be signed in to change notification settings - Fork 115
/
Copy pathAvWaveform.js
421 lines (402 loc) · 9.97 KB
/
AvWaveform.js
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
import axios from 'axios'
import BaseMixin from './AvBase'
/**
* Component props
*/
const props = {
/**
* prop: 'canv-width'
* Canvas element width. Default 500
*/
canvWidth: {
type: Number,
default: 500
},
/**
* prop: 'canv-height'
* Canvas element height. Default 80
*/
canvHeight: {
type: Number,
default: 80
},
/**
* prop: 'played-line-width'
* Waveform line width for played segment of audio
* Default: 0.5
*/
playedLineWidth: {
type: Number,
default: 0.5
},
/**
* prop: 'played-line-color'
* Waveform line color for played segment of audio
* Default: navy
*/
playedLineColor: {
type: String,
default: 'navy'
},
/**
* prop: 'noplayed-line-width'
* Waveform line width for not yet played segment of audio
* Default: 0.5
*/
noplayedLineWidth: {
type: Number,
default: 0.5
},
/**
* prop: 'noplayed-line-color'
* Waveform line color for not yet played segment of audio
* Default: lime
*/
noplayedLineColor: {
type: String,
default: 'lime'
},
/**
* prop: 'playtime'
* Display played time next to progress slider.
* Default: true
*/
playtime: {
type: Boolean,
default: true
},
/**
* prop: 'playtime-with-ms'
* Display milliseconds in played when true.
* For example: 02:55.054
* Default: true
*/
playtimeWithMs: {
type: Boolean,
default: true
},
/**
* prop: 'playtime-font-size'
* Played time print font size in pixels.
* Default: 12
*/
playtimeFontSize: {
type: Number,
default: 12
},
/**
* prop: 'playtime-font-family'
* Played time print font family.
* Default: monospace
*/
playtimeFontFamily: {
type: String,
default: 'monospace'
},
/**
* prop: 'playtime-font-color'
* Played time print font RGB color string.
* Default: grey
*/
playtimeFontColor: {
type: String,
default: 'grey'
},
/**
* prop: 'playtime-text-bottom'
* Position playtime text bottom.
* Default on top.
* Default: false
*/
playtimeTextBottom: {
type: Boolean,
default: false
},
/**
* prop: 'playtime-slider'
* Draw played slider
* Default: true
*/
playtimeSlider: {
type: Boolean,
default: true
},
/**
* prop: 'playtime-slider-color'
* Played slider color
* Default: red
*/
playtimeSliderColor: {
type: String,
default: 'red'
},
/**
* prop: 'playtime-slider-width'
* Played slider width
* Default: 1
*/
playtimeSliderWidth: {
type: Number,
default: 1
},
/**
* prop: 'playtime-clickable'
* Allow click on waveform to change playtime.
* Default: true
*/
playtimeClickable: {
type: Boolean,
default: true
},
/**
* prop: 'requester'
* Allow set a custom requester (axios/fetch) to be used.
* Default: new axios instance
*/
requester: {
type: Function,
default: axios
}
}
/**
* Component AvLine
*/
const AvWaveform = {
name: 'av-waveform',
mixins: [BaseMixin],
props,
data () {
return {
animId: null,
ctxWrapper: null,
ctx: null,
audio: null,
duration: null,
peaks: []
}
},
mounted () {
const conf = {
responseType: 'arraybuffer',
onDownloadProgress: this.downloadProgress
}
this.requester.get(this.audio.src, conf)
.then(response => this.decode(response))
.catch(err => {
console.error(`Failed to get file '${this.audio.src}'`)
console.log(err)
})
this.audio.onplay = () => {
this.$emit('playing')
this.animId = requestAnimationFrame(this.waveformAnim)
}
this.audio.onpause = () => {
this.$emit('paused')
cancelAnimationFrame(this.animId)
this.animId = null
}
this.audio.onended = () => {
this.$emit('ended')
}
},
methods: {
// Stub set analyser method from Mixin AvBase
// as there is no need of analyser in that component
// this method is called from mixin mounted()
setAnalyser: function () {
/* istanbul ignore next */
return null
},
// Stub mainLoop method from Mixin AvBase as
// here different init method will be used.
// This method is called from mixin mounted()
mainLoop: function () {
/* istanbul ignore next */
return null
},
/**
* Decode audio source response array buffer
*/
decode: function (response) {
/* istanbul ignore next */
const ctx = new AudioContext()
/* istanbul ignore next */
ctx.decodeAudioData(response.data, (audioBuffer) => {
this.setPeaks(audioBuffer)
}, (err) => {
console.error('Failed to decode audio data.')
console.log(err)
})
},
/**
* Set peaks array for waveform.
* For now use only one channel
*/
setPeaks: function (buffer) {
const peaks = []
let min = 0
let max = 0
let top = 0
let bottom = 0
const segSize = Math.ceil(buffer.length / this.canvWidth)
const width = this.canvWidth
const height = this.canvHeight
this.duration = buffer.duration // while we have buffer why we don't use it ?
for (let c = 0; c < buffer.numberOfChannels; c++) {
const data = buffer.getChannelData(c)
for (let s = 0; s < width; s++) {
const start = ~~(s * segSize)
const end = ~~(start + segSize)
min = 0
max = 0
for (let i = start; i < end; i++) {
min = data[i] < min ? data[i] : min
max = data[i] > max ? data[i] : max
}
// merge multi channel data
if (peaks[s]) {
peaks[s][0] = peaks[s][0] < max ? max : peaks[s][0]
peaks[s][1] = peaks[s][1] > min ? min : peaks[s][1]
}
peaks[s] = [max, min]
}
}
// set peaks relativelly to canvas dimensions
for (let i = 0; i < peaks.length; i++) {
max = peaks[i][0]
min = peaks[i][1]
top = ((height / 2) - (max * height / 2))
bottom = ((height / 2) - (min * height / 2))
peaks[i] = [top, bottom === top ? top + 1 : bottom]
}
this.peaks = peaks
if (this.playtimeClickable) {
this.ctxWrapper.addEventListener('click', (e) => this.updateTime(e))
}
this.waveform()
},
/**
* Draw wave form.
*/
waveform: function () {
const peaks = this.peaks
const time = this.audio.currentTime
const playX = this.playX(time)
let x = 0
this.ctx.clearRect(0, 0, this.canvWidth, this.canvHeight)
x = this.draw(peaks.slice(0, playX), this.playedLineWidth, this.playedLineColor, x)
this.draw(peaks.slice(playX), this.noplayedLineWidth, this.noplayedLineColor, x)
this.drawSlider(time)
if (this.playtime) this.drawTime(time)
},
/**
* Waveform animation proxy
*/
waveformAnim: function () {
this.waveform()
this.animId = requestAnimationFrame(this.waveformAnim)
},
/**
* Draw segment.
*/
draw: function (data, lineWidth, color, x) {
this.ctx.lineWidth = lineWidth
this.ctx.strokeStyle = color
this.ctx.beginPath()
data.forEach(v => {
this.ctx.moveTo(x, v[0])
this.ctx.lineTo(x, v[1])
x++
})
this.ctx.stroke()
return x
},
/**
* Formatted string of current play time.
* @param {Number} Current play time
* @return {String}
*/
timeFormat: function (timeSec) {
let frmStr = ''
const time = parseFloat(timeSec)
if (isNaN(time)) {
return frmStr
}
const min = ~~(time / 60)
const sec = ~~(time % 60)
const ms = ~~(time % 1 * 1000)
frmStr = (min < 10) ? `0${min}:` : `${min}:`
frmStr += `0${sec}`.substr(-2)
if (this.playtimeWithMs) {
frmStr += '.' + `00${ms}`.substr(-3)
}
return frmStr
},
/**
* Draw play time next to slider.
* @param {Number} Played time sec.millisec.
* @return {Void}
*/
drawTime: function (time) {
const timeStr = this.timeFormat(time)
const offset = 3
const textWidth = ~~this.ctx.measureText(timeStr).width
const playX = this.playX(time)
const textX = playX > (this.canvWidth - textWidth - offset)
? playX - textWidth - offset
: playX + offset
const textY = this.playtimeTextBottom
? this.canvHeight - this.playtimeFontSize + offset
: this.playtimeFontSize + offset
this.ctx.fillStyle = this.playtimeFontColor
this.ctx.font = `${this.playtimeFontSize}px ${this.playtimeFontFamily}`
this.ctx.fillText(timeStr, textX, textY)
},
/**
* Draw played slider.
* @param {Number} Played time sec.millisec.
* @return {Void}
*/
drawSlider: function (time) {
const playX = this.playX(time)
this.ctx.lineWidth = this.playtimeSliderWidth
this.ctx.strokeStyle = this.playtimeSliderColor
this.ctx.beginPath()
this.ctx.moveTo(playX, 0)
this.ctx.lineTo(playX, this.canvHeight)
this.ctx.stroke()
},
/**
* Get x coodrinate for play time.
* @param {Number}
* @return {Number}
*/
playX: function (time) {
return ~~(time / this.duration * this.canvWidth)
},
/**
* Audio playback update time callback.
* @param event
*/
updateTime: function (e) {
this.audio.currentTime = e.offsetX / this.canvWidth * this.duration
if (!this.animId) {
// re-draw if animation is not running
this.waveform()
}
},
/**
* Audio source download progress
*/
downloadProgress: function (ev) {
const progressX = Math.round(ev.loaded / ev.total * this.canvWidth)
this.ctx.clearRect(0, 0, this.canvWidth, this.canvHeight)
this.ctx.beginPath()
this.ctx.strokeStyle = this.noplayedLineColor
this.ctx.moveTo(0, this.canvHeight / 2)
this.ctx.lineTo(progressX, this.canvHeight / 2)
this.ctx.stroke()
}
}
}
export default AvWaveform