wavesurfer.js 6.5.0 → 7.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/.eslintrc.json +24 -0
  2. package/.prettierrc +8 -0
  3. package/README.md +26 -117
  4. package/dist/base-plugin.d.ts +10 -0
  5. package/dist/base-plugin.js +13 -0
  6. package/dist/decoder.d.ts +10 -0
  7. package/dist/decoder.js +43 -0
  8. package/dist/event-emitter.d.ts +11 -0
  9. package/dist/event-emitter.js +21 -0
  10. package/dist/fetcher.d.ts +4 -0
  11. package/dist/fetcher.js +17 -0
  12. package/dist/index.d.ts +92 -0
  13. package/dist/index.js +166 -0
  14. package/dist/player-webaudio.d.ts +8 -0
  15. package/dist/player-webaudio.js +31 -0
  16. package/dist/player.d.ts +16 -0
  17. package/dist/player.js +40 -0
  18. package/dist/plugins/regions.d.ts +48 -0
  19. package/dist/plugins/regions.js +183 -0
  20. package/dist/renderer.d.ts +34 -0
  21. package/dist/renderer.js +193 -0
  22. package/dist/timer.d.ts +10 -0
  23. package/dist/timer.js +17 -0
  24. package/examples/audio.ogg +0 -0
  25. package/examples/bars.js +19 -0
  26. package/examples/basic.js +8 -0
  27. package/examples/gradient.js +28 -0
  28. package/examples/regions.js +63 -0
  29. package/examples/video.js +19 -0
  30. package/examples/webaudio.js +14 -0
  31. package/package.json +19 -99
  32. package/src/base-plugin.ts +20 -0
  33. package/src/decoder.ts +41 -0
  34. package/src/event-emitter.ts +35 -0
  35. package/src/fetcher.ts +7 -0
  36. package/src/index.ts +252 -0
  37. package/src/player-webaudio.ts +34 -0
  38. package/src/player.ts +50 -0
  39. package/src/plugins/regions.ts +240 -0
  40. package/src/renderer.ts +250 -0
  41. package/src/timer.ts +27 -0
  42. package/tsconfig.json +105 -0
  43. package/tutorial/index.html +47 -0
  44. package/tutorial/src/editor.js +70 -0
  45. package/tutorial/src/init.js +66 -0
  46. package/tutorial/src/url.js +25 -0
  47. package/tutorial/style.css +211 -0
  48. package/yarn-error.log +1049 -0
  49. package/LICENSE +0 -29
  50. package/dist/plugin/wavesurfer.cursor.js +0 -418
  51. package/dist/plugin/wavesurfer.cursor.js.map +0 -1
  52. package/dist/plugin/wavesurfer.cursor.min.js +0 -7
  53. package/dist/plugin/wavesurfer.cursor.min.js.map +0 -1
  54. package/dist/plugin/wavesurfer.elan.js +0 -381
  55. package/dist/plugin/wavesurfer.elan.js.map +0 -1
  56. package/dist/plugin/wavesurfer.elan.min.js +0 -7
  57. package/dist/plugin/wavesurfer.elan.min.js.map +0 -1
  58. package/dist/plugin/wavesurfer.markers.js +0 -520
  59. package/dist/plugin/wavesurfer.markers.js.map +0 -1
  60. package/dist/plugin/wavesurfer.markers.min.js +0 -7
  61. package/dist/plugin/wavesurfer.markers.min.js.map +0 -1
  62. package/dist/plugin/wavesurfer.mediasession.js +0 -181
  63. package/dist/plugin/wavesurfer.mediasession.js.map +0 -1
  64. package/dist/plugin/wavesurfer.mediasession.min.js +0 -7
  65. package/dist/plugin/wavesurfer.mediasession.min.js.map +0 -1
  66. package/dist/plugin/wavesurfer.microphone.js +0 -466
  67. package/dist/plugin/wavesurfer.microphone.js.map +0 -1
  68. package/dist/plugin/wavesurfer.microphone.min.js +0 -7
  69. package/dist/plugin/wavesurfer.microphone.min.js.map +0 -1
  70. package/dist/plugin/wavesurfer.minimap.js +0 -440
  71. package/dist/plugin/wavesurfer.minimap.js.map +0 -1
  72. package/dist/plugin/wavesurfer.minimap.min.js +0 -7
  73. package/dist/plugin/wavesurfer.minimap.min.js.map +0 -1
  74. package/dist/plugin/wavesurfer.playhead.js +0 -300
  75. package/dist/plugin/wavesurfer.playhead.js.map +0 -1
  76. package/dist/plugin/wavesurfer.playhead.min.js +0 -7
  77. package/dist/plugin/wavesurfer.playhead.min.js.map +0 -1
  78. package/dist/plugin/wavesurfer.regions.js +0 -1342
  79. package/dist/plugin/wavesurfer.regions.js.map +0 -1
  80. package/dist/plugin/wavesurfer.regions.min.js +0 -7
  81. package/dist/plugin/wavesurfer.regions.min.js.map +0 -1
  82. package/dist/plugin/wavesurfer.spectrogram.js +0 -736
  83. package/dist/plugin/wavesurfer.spectrogram.js.map +0 -1
  84. package/dist/plugin/wavesurfer.spectrogram.min.js +0 -7
  85. package/dist/plugin/wavesurfer.spectrogram.min.js.map +0 -1
  86. package/dist/plugin/wavesurfer.timeline.js +0 -649
  87. package/dist/plugin/wavesurfer.timeline.js.map +0 -1
  88. package/dist/plugin/wavesurfer.timeline.min.js +0 -7
  89. package/dist/plugin/wavesurfer.timeline.min.js.map +0 -1
  90. package/dist/wavesurfer-html-init.js +0 -381
  91. package/dist/wavesurfer-html-init.js.map +0 -1
  92. package/dist/wavesurfer-html-init.min.js +0 -7
  93. package/dist/wavesurfer-html-init.min.js.map +0 -1
  94. package/dist/wavesurfer.js +0 -6145
  95. package/dist/wavesurfer.js.map +0 -1
  96. package/dist/wavesurfer.min.js +0 -7
  97. package/dist/wavesurfer.min.js.map +0 -1
  98. package/src/drawer.canvasentry.js +0 -427
  99. package/src/drawer.js +0 -413
  100. package/src/drawer.multicanvas.js +0 -617
  101. package/src/html-init.js +0 -241
  102. package/src/mediaelement-webaudio.js +0 -77
  103. package/src/mediaelement.js +0 -443
  104. package/src/peakcache.js +0 -127
  105. package/src/plugin/cursor/index.js +0 -350
  106. package/src/plugin/elan/index.js +0 -307
  107. package/src/plugin/markers/index.js +0 -436
  108. package/src/plugin/mediasession/index.js +0 -94
  109. package/src/plugin/microphone/index.js +0 -415
  110. package/src/plugin/minimap/index.js +0 -403
  111. package/src/plugin/playhead/index.js +0 -226
  112. package/src/plugin/regions/index.js +0 -478
  113. package/src/plugin/regions/region.js +0 -883
  114. package/src/plugin/spectrogram/fft.js +0 -222
  115. package/src/plugin/spectrogram/index.js +0 -522
  116. package/src/plugin/timeline/index.js +0 -600
  117. package/src/util/absMax.js +0 -16
  118. package/src/util/clamp.js +0 -11
  119. package/src/util/fetch.js +0 -222
  120. package/src/util/frame.js +0 -13
  121. package/src/util/get-id.js +0 -22
  122. package/src/util/index.js +0 -14
  123. package/src/util/max.js +0 -16
  124. package/src/util/min.js +0 -16
  125. package/src/util/observer.js +0 -144
  126. package/src/util/orientation.js +0 -98
  127. package/src/util/prevent-click.js +0 -19
  128. package/src/util/request-animation-frame.js +0 -15
  129. package/src/util/silence-mode.js +0 -42
  130. package/src/util/style.js +0 -16
  131. package/src/wavesurfer.js +0 -1797
  132. package/src/webaudio.js +0 -779
@@ -0,0 +1,240 @@
1
+ import BasePlugin from '../base-plugin.js'
2
+ import { WaveSurferPluginParams } from '../index.js'
3
+
4
+ const MIN_WIDTH = 10
5
+
6
+ type Region = {
7
+ startTime: number
8
+ endTime: number
9
+ title: string
10
+ start: number
11
+ end: number
12
+ element: HTMLElement
13
+ }
14
+
15
+ type RegionsPluginEvents = {
16
+ 'region-created': { region: Region }
17
+ 'region-updated': { region: Region }
18
+ 'region-clicked': { region: Region }
19
+ }
20
+
21
+ class RegionsPlugin extends BasePlugin<RegionsPluginEvents> {
22
+ private dragStart = NaN
23
+ private container: HTMLElement
24
+ private regions: Region[] = []
25
+ private createdRegion: Region | null = null
26
+ private modifiedRegion: Region | null = null
27
+ private isResizingLeft = false
28
+ private isMoving = false
29
+
30
+ /** Create an instance of RegionsPlugin */
31
+ constructor(params: WaveSurferPluginParams) {
32
+ super(params)
33
+
34
+ this.container = this.initContainer()
35
+
36
+ const unsubscribeReady = this.wavesurfer.on('ready', () => {
37
+ const wrapper = this.renderer.getContainer()
38
+ wrapper.appendChild(this.container)
39
+ unsubscribeReady()
40
+ })
41
+ this.subscriptions.push(unsubscribeReady)
42
+
43
+ const wsContainer = this.renderer.getContainer()
44
+ wsContainer.addEventListener('mousedown', this.handleMouseDown)
45
+ document.addEventListener('mousemove', this.handleMouseMove)
46
+ document.addEventListener('mouseup', this.handleMouseUp)
47
+ }
48
+
49
+ /** Unmounts the regions */
50
+ public destroy() {
51
+ this.renderer.getContainer().removeEventListener('mousedown', this.handleMouseDown)
52
+ document.removeEventListener('mousemove', this.handleMouseMove)
53
+ document.removeEventListener('mouseup', this.handleMouseUp, true)
54
+
55
+ this.container?.remove()
56
+
57
+ super.destroy()
58
+ }
59
+
60
+ private initContainer(): HTMLElement {
61
+ const div = document.createElement('div')
62
+ div.style.position = 'absolute'
63
+ div.style.top = '0'
64
+ div.style.left = '0'
65
+ div.style.width = '100%'
66
+ div.style.height = '100%'
67
+ div.style.zIndex = '3'
68
+ div.style.pointerEvents = 'none'
69
+ return div
70
+ }
71
+
72
+ private handleMouseDown = (e: MouseEvent) => {
73
+ this.dragStart = e.clientX - this.container.getBoundingClientRect().left
74
+ }
75
+
76
+ private handleMouseMove = (e: MouseEvent) => {
77
+ const dragEnd = e.clientX - this.container.getBoundingClientRect().left
78
+
79
+ if (this.modifiedRegion && this.isMoving) {
80
+ this.moveRegion(this.modifiedRegion, dragEnd - this.dragStart)
81
+ this.dragStart = dragEnd
82
+ return
83
+ }
84
+
85
+ if (this.modifiedRegion) {
86
+ this.updateRegion(
87
+ this.modifiedRegion,
88
+ this.isResizingLeft ? dragEnd : undefined,
89
+ this.isResizingLeft ? undefined : dragEnd,
90
+ )
91
+ return
92
+ }
93
+
94
+ if (!isNaN(this.dragStart)) {
95
+ const dragEnd = e.clientX - this.container.getBoundingClientRect().left
96
+
97
+ if (dragEnd - this.dragStart >= MIN_WIDTH) {
98
+ if (!this.createdRegion) {
99
+ this.renderer.getContainer().style.pointerEvents = 'none'
100
+
101
+ this.createdRegion = this.createRegion(this.dragStart, dragEnd)
102
+ } else {
103
+ this.updateRegion(this.createdRegion, this.dragStart, dragEnd)
104
+ }
105
+ }
106
+ }
107
+ }
108
+
109
+ private handleMouseUp = () => {
110
+ if (this.createdRegion) {
111
+ this.addRegion(this.createdRegion)
112
+ this.createdRegion = null
113
+ }
114
+ this.modifiedRegion = null
115
+ this.isMoving = false
116
+ this.dragStart = NaN
117
+ this.renderer.getContainer().style.pointerEvents = ''
118
+ }
119
+
120
+ private createRegionElement(start: number, end: number, title = ''): HTMLElement {
121
+ const el = document.createElement('div')
122
+ el.style.position = 'absolute'
123
+ el.style.left = `${start}px`
124
+ el.style.width = `${end - start}px`
125
+ el.style.height = '100%'
126
+ el.style.backgroundColor = 'rgba(0, 0, 0, 0.1)'
127
+ el.style.transition = 'background-color 0.2s ease'
128
+ el.style.cursor = 'move'
129
+ el.style.pointerEvents = 'all'
130
+ el.title = title
131
+
132
+ const leftHandle = document.createElement('div')
133
+ leftHandle.style.position = 'absolute'
134
+ leftHandle.style.left = '0'
135
+ leftHandle.style.width = '6px'
136
+ leftHandle.style.height = '100%'
137
+ leftHandle.style.borderLeft = '2px solid rgba(0, 0, 0, 0.5)'
138
+ leftHandle.style.cursor = 'ew-resize'
139
+ leftHandle.style.pointerEvents = 'all'
140
+ el.appendChild(leftHandle)
141
+
142
+ const rightHandle = document.createElement('div')
143
+ rightHandle.style.position = 'absolute'
144
+ rightHandle.style.right = '0'
145
+ rightHandle.style.width = '6px'
146
+ rightHandle.style.height = '100%'
147
+ rightHandle.style.borderRight = '2px solid rgba(0, 0, 0, 0.5)'
148
+ rightHandle.style.cursor = 'ew-resize'
149
+ rightHandle.style.pointerEvents = 'all'
150
+ el.appendChild(rightHandle)
151
+
152
+ leftHandle.addEventListener('mousedown', (e) => {
153
+ e.stopPropagation()
154
+ this.modifiedRegion = this.regions.find((r) => r.element === el) || null
155
+ this.isResizingLeft = true
156
+ this.isMoving = false
157
+ })
158
+
159
+ rightHandle.addEventListener('mousedown', (e) => {
160
+ e.stopPropagation()
161
+ this.modifiedRegion = this.regions.find((r) => r.element === el) || null
162
+ this.isResizingLeft = false
163
+ this.isMoving = false
164
+ })
165
+
166
+ el.addEventListener('mousedown', () => {
167
+ this.modifiedRegion = this.regions.find((r) => r.element === el) || null
168
+ this.isMoving = true
169
+ })
170
+
171
+ el.addEventListener('click', () => {
172
+ const region = this.regions.find((r) => r.element === el)
173
+ if (region) {
174
+ this.emit('region-clicked', { region })
175
+ }
176
+ })
177
+
178
+ this.container.appendChild(el)
179
+
180
+ return el
181
+ }
182
+
183
+ private createRegion(start: number, end: number, title = ''): Region {
184
+ const duration = this.wavesurfer.getDuration()
185
+ const width = this.container.clientWidth
186
+
187
+ return {
188
+ element: this.createRegionElement(start, end, title),
189
+ start,
190
+ end,
191
+ startTime: (start / width) * duration,
192
+ endTime: (end / width) * duration,
193
+ title,
194
+ }
195
+ }
196
+
197
+ private addRegion(region: Region) {
198
+ this.regions.push(region)
199
+
200
+ this.emit('region-created', { region })
201
+ }
202
+
203
+ private updateRegion(region: Region, start?: number, end?: number) {
204
+ if (start != null) {
205
+ region.start = start ?? region.start
206
+ region.element.style.left = `${region.start}px`
207
+ region.startTime = (start / this.container.clientWidth) * this.wavesurfer.getDuration()
208
+ }
209
+
210
+ if (end != null) {
211
+ region.end = end
212
+ region.element.style.width = `${region.end - region.start}px`
213
+ region.endTime = (end / this.container.clientWidth) * this.wavesurfer.getDuration()
214
+ }
215
+
216
+ this.emit('region-updated', { region })
217
+ }
218
+
219
+ private moveRegion(region: Region, delta: number) {
220
+ this.updateRegion(region, region.start + delta, region.end + delta)
221
+ }
222
+
223
+ /** Create a region at a given start and end time, with an optional title */
224
+ public addRegionAtTime(startTime: number, endTime: number, title = '') {
225
+ const duration = this.wavesurfer.getDuration()
226
+ const width = this.container.clientWidth
227
+ const start = (startTime / duration) * width
228
+ const end = (endTime / duration) * width
229
+ const region = this.createRegion(start, end, title)
230
+ this.addRegion(region)
231
+ return region
232
+ }
233
+
234
+ /** Set the background color of a region */
235
+ public setRegionColor(region: Region, color: string) {
236
+ region.element.style.backgroundColor = color
237
+ }
238
+ }
239
+
240
+ export default RegionsPlugin
@@ -0,0 +1,250 @@
1
+ import EventEmitter from './event-emitter.js'
2
+
3
+ type RendererOptions = {
4
+ container: HTMLElement | string | null
5
+ height: number
6
+ waveColor: string
7
+ progressColor: string
8
+ minPxPerSec: number
9
+ barWidth?: number
10
+ barGap?: number
11
+ barRadius?: number
12
+ }
13
+
14
+ type RendererEvents = {
15
+ click: { relativeX: number }
16
+ }
17
+
18
+ class Renderer extends EventEmitter<RendererEvents> {
19
+ private options: RendererOptions
20
+ private container: HTMLElement
21
+ private shadowRoot: ShadowRoot
22
+ private mainCanvas: HTMLCanvasElement
23
+ private progressCanvas: HTMLCanvasElement
24
+ private cursor: HTMLElement
25
+ private ctx: CanvasRenderingContext2D
26
+
27
+ constructor(options: RendererOptions) {
28
+ super()
29
+
30
+ this.options = options
31
+
32
+ let container: HTMLElement | null = null
33
+ if (typeof this.options.container === 'string') {
34
+ container = document.querySelector(this.options.container)
35
+ } else if (this.options.container instanceof HTMLElement) {
36
+ container = this.options.container
37
+ }
38
+ if (!container) {
39
+ throw new Error('Container not found')
40
+ }
41
+
42
+ const div = document.createElement('div')
43
+ const shadow = div.attachShadow({ mode: 'open' })
44
+
45
+ shadow.innerHTML = `
46
+ <style>
47
+ :host .scroll {
48
+ overflow-x: auto;
49
+ overflow-y: visible;
50
+ user-select: none;
51
+ width: 100%;
52
+ height: ${this.options.height}px;
53
+ position: relative;
54
+ }
55
+ :host .wrapper {
56
+ position: relative;
57
+ width: fit-content;
58
+ min-width: 100%;
59
+ height: 100%;
60
+ z-index: 2;
61
+ }
62
+ :host canvas {
63
+ display: block;
64
+ height: 100%;
65
+ min-width: 100%;
66
+ image-rendering: pixelated;
67
+ }
68
+ :host .progress {
69
+ position: absolute;
70
+ z-index: 2;
71
+ top: 0;
72
+ left: 0;
73
+ height: 100%;
74
+ pointer-events: none;
75
+ clip-path: inset(100%);
76
+ }
77
+ :host .cursor {
78
+ position: absolute;
79
+ z-index: 3;
80
+ top: 0;
81
+ left: 0;
82
+ height: 100%;
83
+ border-right: 1px solid ${this.options.progressColor};
84
+ }
85
+ </style>
86
+
87
+ <div class="scroll">
88
+ <div class="wrapper">
89
+ <canvas></canvas>
90
+ <canvas class="progress"></canvas>
91
+ <div class="cursor"></div>
92
+ </div>
93
+ </div>
94
+ `
95
+
96
+ this.container = div
97
+ this.shadowRoot = shadow
98
+ this.mainCanvas = shadow.querySelector('canvas') as HTMLCanvasElement
99
+ this.ctx = this.mainCanvas.getContext('2d', { desynchronized: true }) as CanvasRenderingContext2D
100
+ this.progressCanvas = shadow.querySelector('.progress') as HTMLCanvasElement
101
+ this.cursor = shadow.querySelector('.cursor') as HTMLElement
102
+ container.appendChild(div)
103
+
104
+ this.mainCanvas.addEventListener('click', (e) => {
105
+ const rect = this.mainCanvas.getBoundingClientRect()
106
+ const x = e.clientX - rect.left
107
+ const relativeX = x / rect.width
108
+ this.emit('click', { relativeX })
109
+ })
110
+ }
111
+
112
+ destroy() {
113
+ this.container.remove()
114
+ }
115
+
116
+ private renderLinePeaks(channelData: Float32Array[], width: number, height: number) {
117
+ const { ctx } = this
118
+ ctx.clearRect(0, 0, width, height)
119
+ ctx.beginPath()
120
+ ctx.moveTo(0, height / 2)
121
+
122
+ // Channel 0 is left, 1 is right
123
+ const leftChannel = channelData[0]
124
+ const isMono = channelData.length === 1
125
+ const rightChannel = isMono ? leftChannel : channelData[1]
126
+
127
+ // Draw left channel in the top half of the canvas
128
+ let prevX = -1
129
+ let prevY = 0
130
+ for (let i = 0, len = leftChannel.length; i < len; i++) {
131
+ const x = Math.round((i / leftChannel.length) * width)
132
+ const y = Math.round(((1 - leftChannel[i]) * height) / 2)
133
+ if (x !== prevX || y > prevY) {
134
+ ctx.lineTo(x, y)
135
+ prevX = x
136
+ prevY = y
137
+ }
138
+ }
139
+
140
+ // Draw right channel in the bottom half of the canvas
141
+ prevX = -1
142
+ prevY = 0
143
+ for (let i = rightChannel.length - 1; i >= 0; i--) {
144
+ const x = Math.round((i / rightChannel.length) * width)
145
+ const y = Math.round(((1 + rightChannel[i]) * height) / 2)
146
+ if (x !== prevX || (isMono ? y < -prevY : y > prevY)) {
147
+ ctx.lineTo(x, y)
148
+ prevX = x
149
+ prevY = y
150
+ }
151
+ }
152
+
153
+ ctx.strokeStyle = ctx.fillStyle = this.options.waveColor
154
+ ctx.stroke()
155
+ ctx.fill()
156
+ }
157
+
158
+ private renderBarPeaks(channelData: Float32Array[], width: number, height: number) {
159
+ const { devicePixelRatio } = window
160
+ const { ctx } = this
161
+ ctx.clearRect(0, 0, width, height)
162
+
163
+ const barWidthOption = this.options.barWidth || 1
164
+ const barWidth = barWidthOption * devicePixelRatio
165
+ const barGap = (this.options.barGap ?? barWidthOption / 2) * devicePixelRatio
166
+ const barRadius = this.options.barRadius ?? 0
167
+
168
+ const leftChannel = channelData[0]
169
+ const isMono = channelData.length === 1
170
+ const rightChannel = isMono ? leftChannel : channelData[1]
171
+
172
+ const barCount = Math.floor(width / (barWidth + barGap))
173
+
174
+ const leftChannelBars = new Float32Array(barCount)
175
+ const rightChannelBars = new Float32Array(barCount)
176
+
177
+ const barIndexScale = barCount / leftChannel.length
178
+ const leftChannelLength = leftChannel.length
179
+ for (let i = 0; i < leftChannelLength; i++) {
180
+ const barIndex = Math.round(i * barIndexScale)
181
+ leftChannelBars[barIndex] = Math.max(leftChannelBars[barIndex], leftChannel[i])
182
+ rightChannelBars[barIndex] = (isMono ? Math.min : Math.max)(rightChannelBars[barIndex], rightChannel[i])
183
+ }
184
+
185
+ ctx.beginPath()
186
+
187
+ for (let i = 0; i < barCount; i++) {
188
+ const leftBarHeight = Math.max(1, Math.round((leftChannelBars[i] * height) / 2))
189
+ const rightBarHeight = Math.max(1, Math.round(Math.abs(rightChannelBars[i] * height) / 2))
190
+
191
+ ctx.roundRect(
192
+ i * (barWidth + barGap),
193
+ height / 2 - leftBarHeight,
194
+ barWidth,
195
+ leftBarHeight + rightBarHeight,
196
+ barRadius,
197
+ )
198
+ }
199
+
200
+ ctx.fillStyle = this.options.waveColor
201
+ ctx.fill()
202
+ }
203
+
204
+ render(channelData: Float32Array[], duration: number, minPxPerSec = this.options.minPxPerSec) {
205
+ const { devicePixelRatio } = window
206
+ const width = Math.max(this.container.clientWidth * devicePixelRatio, duration * minPxPerSec)
207
+ const { height } = this.options
208
+ this.mainCanvas.width = width
209
+ this.mainCanvas.height = height
210
+ this.mainCanvas.style.width = Math.round(width / devicePixelRatio) + 'px'
211
+
212
+ const renderingFn = this.options.barWidth ? this.renderBarPeaks : this.renderLinePeaks
213
+ renderingFn.call(this, channelData, width, height)
214
+ this.createProgressMask()
215
+ }
216
+
217
+ private createProgressMask() {
218
+ const progressCtx = this.progressCanvas.getContext('2d', { desynchronized: true })
219
+ if (!progressCtx) {
220
+ throw new Error('Failed to get canvas context')
221
+ }
222
+ this.progressCanvas.width = this.mainCanvas.width
223
+ this.progressCanvas.height = this.mainCanvas.height
224
+ this.progressCanvas.style.width = this.mainCanvas.style.width
225
+ this.progressCanvas.style.height = this.mainCanvas.style.height
226
+ progressCtx.drawImage(this.mainCanvas, 0, 0)
227
+ progressCtx.globalCompositeOperation = 'source-in'
228
+ progressCtx.fillStyle = this.options.progressColor
229
+ progressCtx.fillRect(0, 0, this.progressCanvas.width, this.progressCanvas.height)
230
+ }
231
+
232
+ renderProgress(progress: number, autoCenter = false) {
233
+ this.progressCanvas.style.clipPath = `inset(0 ${100 - progress * 100}% 0 0)`
234
+ this.cursor.style.left = `${progress * 100}%`
235
+
236
+ if (autoCenter) {
237
+ const center = this.container.clientWidth / 2
238
+ const fullWidth = this.mainCanvas.clientWidth
239
+ if (fullWidth * progress >= center) {
240
+ this.container.scrollLeft = fullWidth * progress - center
241
+ }
242
+ }
243
+ }
244
+
245
+ getContainer(): HTMLElement {
246
+ return this.shadowRoot.querySelector('.scroll') as HTMLElement
247
+ }
248
+ }
249
+
250
+ export default Renderer
package/src/timer.ts ADDED
@@ -0,0 +1,27 @@
1
+ import EventEmitter from './event-emitter.js'
2
+
3
+ type TimerEvents = {
4
+ tick: void
5
+ }
6
+
7
+ class Timer extends EventEmitter<TimerEvents> {
8
+ private unsubscribe: () => void = () => undefined
9
+
10
+ constructor() {
11
+ super()
12
+
13
+ this.unsubscribe = this.on('tick', () => {
14
+ requestAnimationFrame(() => {
15
+ this.emit('tick')
16
+ })
17
+ })
18
+
19
+ this.emit('tick')
20
+ }
21
+
22
+ destroy() {
23
+ this.unsubscribe()
24
+ }
25
+ }
26
+
27
+ export default Timer
package/tsconfig.json ADDED
@@ -0,0 +1,105 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig.json to read more about this file */
4
+
5
+ /* Projects */
6
+ // "incremental": true, /* Enable incremental compilation */
7
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
+ // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
9
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
10
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
+
13
+ /* Language and Environment */
14
+ "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
+ "lib": [ "es2019", "dom" ],
16
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
17
+ // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
18
+ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
20
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
22
+ // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
23
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25
+
26
+ /* Modules */
27
+ "module": "esnext",
28
+ // "rootDir": "./", /* Specify the root folder within your source files. */
29
+ // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
30
+ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
31
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
32
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
33
+ // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
34
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
35
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
36
+ // "resolveJsonModule": true, /* Enable importing .json files */
37
+ // "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
38
+
39
+ /* JavaScript Support */
40
+ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
41
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
42
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
43
+
44
+ /* Emit */
45
+ "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
46
+ // "declarationMap": true, /* Create sourcemaps for d.ts files. */
47
+ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
48
+ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
49
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
50
+ "outDir": "./dist", /* Specify an output folder for all emitted files. */
51
+ // "removeComments": true, /* Disable emitting comments. */
52
+ // "noEmit": true, /* Disable emitting files from a compilation. */
53
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
54
+ // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
55
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
56
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
57
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
58
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
59
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
60
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
61
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
62
+ // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
63
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
64
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
65
+ // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
66
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
67
+ // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
68
+
69
+ /* Interop Constraints */
70
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
71
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
72
+ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
73
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
74
+ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
75
+
76
+ /* Type Checking */
77
+ "strict": true, /* Enable all strict type-checking options. */
78
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
79
+ // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
80
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
81
+ // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
82
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
83
+ // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
84
+ // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
85
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
86
+ // "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
87
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
88
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
89
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
90
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
91
+ // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
92
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
93
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
94
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
95
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
96
+
97
+ /* Completeness */
98
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
99
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
100
+ },
101
+ "exclude": [
102
+ "node_modules",
103
+ "dist"
104
+ ]
105
+ }
@@ -0,0 +1,47 @@
1
+ <html>
2
+ <head>
3
+ <meta charset="utf-8" />
4
+
5
+ <title>wavesurfer.ts examples</title>
6
+
7
+ <link rel="stylesheet" href="style.css" />
8
+
9
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.32.0-dev.20211218/min/vs/loader.min.js" integrity="sha512-O9SYDgWAM3bEzit1z6mkFd+dxKUplO/oB8UwYGAkg2Zy/WzDUQ2mYA/ysk3c0CxiXAN4u8T9JeZ0Ahk2Jj/33Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
10
+ </head>
11
+
12
+ <body>
13
+ <div class="layout">
14
+ <header>
15
+ <h1>wavesurfer.ts examples</h1>
16
+
17
+ <a href="/docs">Documentation</a>
18
+ </header>
19
+
20
+ <div class="grid">
21
+ <div class="sidebar">
22
+ <ul>
23
+ <li><a href="/examples/basic.js">Basic</a></li>
24
+ <li><a href="/examples/regions.js">Regions</a></li>
25
+ <li><a href="/examples/video.js">Video</a></li>
26
+ <li><a href="/examples/bars.js">Bars</a></li>
27
+ <li><a href="/examples/gradient.js">Gradient</a></li>
28
+ <li><a href="/examples/webaudio.js">Web Audio</a></li>
29
+ </ul>
30
+ </div>
31
+
32
+ <div id="editor"></div>
33
+
34
+ <div class="preview">
35
+ <iframe id="preview" sandbox="allow-scripts allow-same-origin"></iframe>
36
+ </div>
37
+ </div>
38
+
39
+ <footer>
40
+ <a class="github" href="https://github.com/katspaugh/wavesurfer.ts">katspaugh/wavesurfer.ts</a>
41
+ This app was built using the <a href="https://microsoft.github.io/monaco-editor/">Monaco editor</a>
42
+ </footer>
43
+ </div>
44
+
45
+ <script type="module" src="src/init.js"></script>
46
+ </body>
47
+ </html>