Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 422 423 424 425 426 427 428 429 430 431 432 | 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 53x 1x 53x 1x 53x 1x 53x 1x 53x 1x 53x 44x 44x 44x 44x 44x 44x 44x 53x 3x 53x 1x 53x 52x 47x 47x 47x 47x 5x 5x 5x 5x 5x 5x 5x 53x 2x 53x 48x 5x 5x 5x 1x 5x 10x 5x 5x 53x 43x 43x 43x 41x 41x 41x 41x 43x 43x 43x 43x 43x 42x 1x 53x 4x 4x 1x 1x 3x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 2x 2x 2x 2x 2x 2x 53x 5x 2x 3x 53x 3x 2x 1x 53x 2x 1x 1x 53x 4x 3x 1x 53x 14x 13x 1x 53x 13x 3x 10x 10x 10x 10x 10x 53x 8x 1x 7x 7x 7x 7x 7x 7x 7x 6x 53x 3x 1x 2x | import * as WS from "wavesurfer.js"
import { EventEmitter } from "eventemitter3"
import { PluginDefinition } from "wavesurfer.js"
import { Channel, PlaybackRate, PlayerOptions, PlayerParams } from "../types"
import { Drawer } from "./renderer"
import { playbackRateToNumeral } from "./misc"
import {
defaultTimelineOptions,
TimelinePlugin,
defaultTimeFormatter,
} from "./plugins/timeline"
import {
regionsContainerStyles,
segmentHighlighterCenterStyles,
segmentHighlighterContainerStyles,
segmentHighlighterLeftStyles,
segmentHighlighterRightStyles,
} from "./styles"
const WaveSurfer: typeof WS = (WS as any).default
const style: WS.WaveSurferUtil["style"] = (WS as any).default.util.style
const defaultPlayerOptions = {
backgroundColor: "#FFFFFF",
progressBackgroundColor: "rgba(184, 216, 190, 0.5)",
barWidth: 4,
barHeight: 0.8,
barGap: 2,
cursorWidth: 2,
cursorColor: "#000",
height: 56,
hideScrollbar: true,
progressColor: "#14972e",
waveColor: "#14972e",
regionColor: "#FEE1CC",
}
type PlayerEvents = {
error: [Error]
finish: []
"hot-load": []
play: []
pause: []
process: [number]
ready: []
redraw: []
seek: [number]
}
export class PlayerCore extends EventEmitter<PlayerEvents> {
container: HTMLDivElement
isHotLoading = false
mediaElement: HTMLMediaElement | null = null
regionsContainer: HTMLDivElement
segmentHighlighterContainer: HTMLDivElement
segmentHighlighterLeft: HTMLDivElement
segmentHighlighterCenter: HTMLDivElement
segmentHighlighterRight: HTMLDivElement
timelineContainer: HTMLDivElement
waveformContainer: HTMLDivElement
waveform?: HTMLElement | null // we need reference to waveform, used as container for regions
ws?: WaveSurfer
wsParams: PlayerParams
private currentSegmentDuration?: number
private currentSegmentOffset?: number
constructor(container: HTMLDivElement, opt: PlayerOptions = {}) {
super()
this.container = container
this.timelineContainer = document.createElement("div")
this.waveformContainer = document.createElement("div")
this.regionsContainer = style(
document.createElement("div"),
regionsContainerStyles
) as HTMLDivElement
this.segmentHighlighterContainer = style(
document.createElement("div"),
segmentHighlighterContainerStyles
) as HTMLDivElement
this.segmentHighlighterLeft = style(
document.createElement("div"),
segmentHighlighterLeftStyles
) as HTMLDivElement
this.segmentHighlighterCenter = style(
document.createElement("div"),
segmentHighlighterCenterStyles
) as HTMLDivElement
this.segmentHighlighterRight = style(
document.createElement("div"),
segmentHighlighterRightStyles
) as HTMLDivElement
this.timelineContainer.setAttribute("class", "twilio-player-timeline")
this.waveformContainer.setAttribute("class", "twilio-player-waveform")
this.regionsContainer.setAttribute("class", "twilio-player-regions")
this.segmentHighlighterContainer.setAttribute(
"class",
"twilio-player-segments"
)
this.segmentHighlighterContainer.appendChild(this.segmentHighlighterLeft)
this.segmentHighlighterContainer.appendChild(this.segmentHighlighterCenter)
this.segmentHighlighterContainer.appendChild(this.segmentHighlighterRight)
this.waveformContainer.appendChild(this.segmentHighlighterContainer)
container.appendChild(this.waveformContainer)
container.appendChild(this.timelineContainer)
const timelineOptions = {
...defaultTimelineOptions,
...opt.timeline,
container: this.timelineContainer,
}
const plugins: PluginDefinition[] = [
TimelinePlugin.create({
...timelineOptions,
formatTimeCallback: this.timelineFormatter,
}),
]
const wsParams: PlayerParams = {
...defaultPlayerOptions,
container: this.waveformContainer,
backend: "MediaElement",
mediaType: "audio",
normalize: true,
plugins,
removeMediaElementOnDestroy: true,
renderer: Drawer,
splitChannels: true,
...opt,
}
this.wsParams = wsParams
}
private initWS() {
this.ws = WaveSurfer.create(this.wsParams)
this.ws.on("pause", this.wsHandlePause)
this.ws.on("play", this.wsHandlePlay)
this.ws.on("ready", this.wsHandleReady)
this.ws.on("seek", this.wsHandleSeek)
this.ws.on("error", this.wsHandleError)
this.ws.on("finish", this.wsHandleFinish)
this.ws.on("audioprocess", this.wsHandleAudioProcess)
this.ws.on("redraw", this.wsHandleRedraw)
return this.ws
}
private wsHandleAudioProcess = (currentTime: number) => {
this.emit("process", currentTime)
}
private wsHandleError = (error: Error) => {
this.emit("error", error)
}
private wsHandleFinish = () => {
this.emit("finish")
}
private wsHandlePlay = () => {
this.emit("play")
}
private wsHandlePause = () => {
this.emit("pause")
}
private wsHandleReady = () => {
// If e.g. error happened (because access to recording was forbidden),
// a "ready" event was not fired. When we then hotreload (because we fetched a new pre-signed url),
// the "ready" event will get fired before the "canplay" event and this.isHotLoading would be truthy,
// and we would get an error if we tried to e.g. seek in response to the ready event.
// We can safely set this.isHotLoading to false.
this.isHotLoading = false
const duration = this.ws?.getDuration()
Iif (duration && this.ws && this.ws.timeline && this.ws.timeline.params) {
this.ws.timeline.params.timeInterval =
Math.floor(duration / 60) + (duration % 60) / 60
}
this.waveform = this.waveformContainer.querySelector("wave") as HTMLElement
this.waveform.appendChild(this.regionsContainer)
this.emit("ready")
this.renderSegmentHighlight()
}
private wsHandleRedraw = () => {
this.emit("redraw")
}
private wsHandleSeek = (progress: number) => {
this.emit("seek", progress)
}
public renderSegmentHighlight = () => {
if (
this.currentSegmentOffset === undefined ||
this.currentSegmentDuration === undefined ||
!this.ws
) {
this.segmentHighlighterLeft.style.width = "0"
this.segmentHighlighterCenter.style.width = "0"
this.segmentHighlighterRight.style.flex = "0"
return
}
const duration = this.ws.getDuration()
const pxPerSec = this.container.clientWidth / duration
const width =
Math.min(
this.currentSegmentDuration,
duration - this.currentSegmentOffset
) * pxPerSec
const offset = this.currentSegmentOffset * pxPerSec
this.segmentHighlighterLeft.style.width = `${offset}px`
this.segmentHighlighterCenter.style.width = `${width}px`
this.segmentHighlighterRight.style.flex = "1"
}
private timelineFormatter = (seconds: number) => {
return defaultTimeFormatter(seconds - (this.currentSegmentOffset || 0))
}
public destroy = () => {
if (this.ws) {
this.ws.drawer.destroy()
this.ws.destroy() // The method removes the media element itself, removes listeners, destroys plugins, cancels all ajax
while (this.timelineContainer.lastChild) {
this.timelineContainer.removeChild(this.timelineContainer.lastChild)
}
Array.from(this.waveformContainer.childNodes).forEach(el => {
if (el.nodeName === "WAVE") {
this.waveformContainer.removeChild(el)
}
})
this.ws = undefined
}
}
public load = (
url: string,
channels: Channel[] = [],
ops?: { isAuthenticatedEndpoint: boolean }
) => {
this.destroy()
this.isHotLoading = false
if (!ops?.isAuthenticatedEndpoint) {
this.mediaElement = document.createElement("audio")
this.mediaElement.setAttribute("preload", "metadata")
this.mediaElement.src = url
this.container.prepend(this.mediaElement)
}
const ws = this.initWS()
;(ws.drawer as Drawer).channels = channels // TODO: Fix in @types/wavesurfer.js
const peaks = (ws.drawer as Drawer).channels.map(c => c.peaks || [])
// If we are using an authenticated endpoint, mediaElement won't be defined, because the audio tag doesn't support auth.
// In that case, we are instead passing the url directly to Wavesurfer player
const playerUrlTarget = this.mediaElement || url
if (!peaks.length || peaks.some(p => !p.length)) {
// If any one of the channel peaks are missing, we just fall back to generating
// peaks by Wavesurfer
ws.load(playerUrlTarget)
} else {
ws.load(playerUrlTarget, peaks)
}
}
public hotLoad = (url: string) => {
return new Promise((resolve, reject) => {
if (!this.ws) {
reject(
new Error(
"Unable to hotload, because player is either loading or not initialized"
)
)
return
}
if (!this.mediaElement) {
reject(
new Error("Unable to hotload, because media element does not exist")
)
return
}
const time = this.ws.getCurrentTime()
const isPlaying = this.isPlaying()
const rate = this.ws.getPlaybackRate()
this.isHotLoading = true
const onCanPlay = () => {
Eif (this.ws && this.mediaElement) {
// @ts-ignore
this.ws.backend.seekTo(time) // TODO: Fix in @types/wavesurfer.js
this.ws.setPlaybackRate(rate)
if (isPlaying) {
// @ts-ignore
this.ws.backend.play() // TODO: Fix in @types/wavesurfer.js
}
this.mediaElement.removeEventListener("canplay", onCanPlay)
this.isHotLoading = false
this.emit("hot-load")
resolve(undefined)
}
}
this.mediaElement.addEventListener("canplay", onCanPlay)
this.mediaElement.src = url
})
}
public play = (start?: number, end?: number) => {
if (!this.ws || this.isHotLoading) {
return Promise.reject(
new Error(
"Unable to play, because player is either loading or not initialized"
)
)
}
return this.ws.play(
start !== undefined
? start + (this.currentSegmentOffset || 0)
: undefined,
end !== undefined ? end + (this.currentSegmentOffset || 0) : undefined
)
}
public pause = () => {
if (!this.ws || this.isHotLoading) {
return Promise.reject(
new Error(
"Unable to pause, because player is either loading or not initialized"
)
)
}
return this.ws.pause() || Promise.resolve()
}
public getCurrentTime = () => {
if (this.ws) {
return this.ws.getCurrentTime() - (this.currentSegmentOffset || 0)
}
return 0
}
public isPlaying = () => {
if (this.ws) {
return this.ws.isPlaying()
}
return false
}
public isReady = () => {
if (this.ws) {
return this.ws.isReady
}
return false
}
public seekToSecond = (
seconds: number,
offsetFromSegment = true,
recordingDuration?: number
) => {
if (!this.ws || !this.isReady() || this.isHotLoading) {
throw new Error(
"Unable to seek, because player is either loading or not initialized"
)
}
const offset =
((offsetFromSegment && this.currentSegmentOffset) || 0) + seconds
const totalDuration = recordingDuration || this.ws.getDuration()
let seekAt = offset / totalDuration
Iif (isNaN(seekAt) || !(seekAt >= 0 && seekAt <= 1)) {
console.warn(
`seekAt value not in range [0,1]. Setting it to 0,Total Recording duration:recordingDuration: ${recordingDuration}, this.ws.getDuration():${this.ws.getDuration()},offset:${offset}, seekAt: ${seekAt}`
)
seekAt = 0
}
return this.ws.seekTo(seekAt)
}
public setCurrentSegment = (duration?: number, offset?: number) => {
if (!this.ws) {
throw new Error(
"Unable to set current segment, because player is either loading or not initialized"
)
}
const recordingDuration = this.ws.getDuration()
Iif (
!Number.isFinite(recordingDuration) ||
(offset && offset > recordingDuration)
) {
console.warn(
"The offset of the current segment is longer than recording duration",
offset,
recordingDuration
)
offset = undefined
duration = undefined
}
this.currentSegmentDuration = duration
this.currentSegmentOffset = offset
this.renderSegmentHighlight()
this.seekToSecond(0, true, recordingDuration)
if (this.ws.timeline) {
this.ws.timeline.render()
}
}
public setPlaybackRate = (rate: PlaybackRate = 1.0) => {
if (!this.ws) {
throw new Error(
"Unable to seek, because player is either loading or not initialized"
)
}
this.ws.setPlaybackRate(playbackRateToNumeral(rate))
}
}
|