wavesurfer.js 7.0.0-alpha.4 → 7.0.0-alpha.41

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 (46) hide show
  1. package/README.md +64 -17
  2. package/dist/base-plugin.d.ts +14 -5
  3. package/dist/base-plugin.js +5 -1
  4. package/dist/decoder.d.ts +8 -10
  5. package/dist/decoder.js +37 -44
  6. package/dist/event-emitter.d.ts +16 -10
  7. package/dist/event-emitter.js +38 -16
  8. package/dist/fetcher.js +2 -13
  9. package/dist/legacy-adapter.d.ts +7 -0
  10. package/dist/legacy-adapter.js +15 -0
  11. package/dist/player.d.ts +32 -11
  12. package/dist/player.js +55 -39
  13. package/dist/plugins/envelope.d.ts +57 -0
  14. package/dist/plugins/envelope.js +305 -0
  15. package/dist/plugins/envelope.min.js +1 -0
  16. package/dist/plugins/minimap.d.ts +34 -0
  17. package/dist/plugins/minimap.js +99 -0
  18. package/dist/plugins/minimap.min.js +1 -0
  19. package/dist/plugins/multitrack.d.ts +117 -0
  20. package/dist/plugins/multitrack.js +506 -0
  21. package/dist/plugins/multitrack.min.js +1 -0
  22. package/dist/plugins/record.d.ts +26 -0
  23. package/dist/plugins/record.js +125 -0
  24. package/dist/plugins/record.min.js +1 -0
  25. package/dist/plugins/regions.d.ts +88 -41
  26. package/dist/plugins/regions.js +365 -170
  27. package/dist/plugins/regions.min.js +1 -0
  28. package/dist/plugins/spectrogram.d.ts +24 -0
  29. package/dist/plugins/spectrogram.js +165 -0
  30. package/dist/plugins/timeline.d.ts +41 -0
  31. package/dist/plugins/timeline.js +135 -0
  32. package/dist/plugins/timeline.min.js +1 -0
  33. package/dist/renderer.d.ts +26 -12
  34. package/dist/renderer.js +212 -157
  35. package/dist/timer.d.ts +1 -1
  36. package/dist/wavesurfer.d.ts +136 -0
  37. package/dist/wavesurfer.js +213 -0
  38. package/dist/wavesurfer.min.js +1 -1
  39. package/package.json +49 -24
  40. package/dist/index.d.ts +0 -104
  41. package/dist/index.js +0 -188
  42. package/dist/player-webaudio.d.ts +0 -8
  43. package/dist/player-webaudio.js +0 -32
  44. package/dist/react/useWavesurfer.d.ts +0 -5
  45. package/dist/react/useWavesurfer.js +0 -20
  46. package/dist/wavesurfer.Regions.min.js +0 -1
@@ -0,0 +1,213 @@
1
+ import Fetcher from './fetcher.js';
2
+ import Decoder from './decoder.js';
3
+ import Renderer from './renderer.js';
4
+ import Player from './player.js';
5
+ import Timer from './timer.js';
6
+ const defaultOptions = {
7
+ height: 128,
8
+ waveColor: '#999',
9
+ progressColor: '#555',
10
+ cursorWidth: 1,
11
+ minPxPerSec: 0,
12
+ fillParent: true,
13
+ interact: true,
14
+ autoCenter: true,
15
+ };
16
+ class WaveSurfer extends Player {
17
+ /** Create a new WaveSurfer instance */
18
+ static create(options) {
19
+ return new WaveSurfer(options);
20
+ }
21
+ /** Create a new WaveSurfer instance */
22
+ constructor(options) {
23
+ super({
24
+ media: options.media,
25
+ autoplay: options.autoplay,
26
+ playbackRate: options.audioRate,
27
+ });
28
+ this.plugins = [];
29
+ this.decodedData = null;
30
+ this.canPlay = false;
31
+ this.options = Object.assign({}, defaultOptions, options);
32
+ this.fetcher = new Fetcher();
33
+ this.timer = new Timer();
34
+ this.renderer = new Renderer({
35
+ container: this.options.container,
36
+ }, this.options);
37
+ this.initPlayerEvents();
38
+ this.initRendererEvents();
39
+ this.initTimerEvents();
40
+ this.initReadyEvent();
41
+ this.initPlugins();
42
+ const url = this.options.url || this.options.media?.src;
43
+ if (url) {
44
+ this.load(url, this.options.peaks, this.options.duration);
45
+ }
46
+ }
47
+ setOptions(options) {
48
+ this.options = { ...this.options, ...options };
49
+ this.renderer.setOptions(this.options);
50
+ }
51
+ initPlayerEvents() {
52
+ this.subscriptions.push(this.onMediaEvent('timeupdate', () => {
53
+ const currentTime = this.getCurrentTime();
54
+ this.renderer.renderProgress(currentTime / this.getDuration(), this.isPlaying());
55
+ this.emit('timeupdate', currentTime);
56
+ }), this.onMediaEvent('play', () => {
57
+ this.emit('play');
58
+ this.timer.start();
59
+ }), this.onMediaEvent('pause', () => {
60
+ this.emit('pause');
61
+ this.timer.stop();
62
+ if (this.getCurrentTime() >= this.getDuration()) {
63
+ this.emit('finish');
64
+ }
65
+ }), this.onMediaEvent('canplay', () => {
66
+ this.canPlay = true;
67
+ this.emit('canplay', this.getDuration());
68
+ }), this.onMediaEvent('seeking', () => {
69
+ this.emit('seeking', this.getCurrentTime());
70
+ }));
71
+ }
72
+ initRendererEvents() {
73
+ // Seek on click
74
+ this.subscriptions.push(this.renderer.on('click', (relativeX) => {
75
+ if (this.options.interact) {
76
+ this.canPlay && this.seekTo(relativeX);
77
+ this.emit('interaction');
78
+ }
79
+ }));
80
+ }
81
+ initTimerEvents() {
82
+ // The timer fires every 16ms for a smooth progress animation
83
+ this.subscriptions.push(this.timer.on('tick', () => {
84
+ const currentTime = this.getCurrentTime();
85
+ this.renderer.renderProgress(currentTime / this.getDuration(), true);
86
+ this.emit('timeupdate', currentTime);
87
+ this.emit('audioprocess', currentTime);
88
+ }));
89
+ }
90
+ initReadyEvent() {
91
+ const emitReady = () => {
92
+ if (this.decodedData && this.canPlay) {
93
+ this.emit('ready', this.getDuration());
94
+ }
95
+ };
96
+ this.subscriptions.push(this.on('decode', emitReady), this.on('canplay', emitReady));
97
+ }
98
+ initPlugins() {
99
+ if (!this.options.plugins?.length)
100
+ return;
101
+ this.options.plugins.forEach((plugin) => {
102
+ this.registerPlugin(plugin);
103
+ });
104
+ }
105
+ /** Register a wavesurfer.js plugin */
106
+ registerPlugin(plugin) {
107
+ plugin.init({
108
+ wavesurfer: this,
109
+ container: this.renderer.getContainer(),
110
+ wrapper: this.renderer.getWrapper(),
111
+ });
112
+ this.plugins.push(plugin);
113
+ return plugin;
114
+ }
115
+ /** Get all registered plugins */
116
+ getActivePlugins() {
117
+ return this.plugins;
118
+ }
119
+ /** Load an audio file by URL, with optional pre-decoded audio data */
120
+ async load(url, channelData, duration) {
121
+ this.decodedData = null;
122
+ this.canPlay = false;
123
+ this.loadUrl(url);
124
+ this.emit('load', url);
125
+ if (channelData) {
126
+ // Pre-decoded audio data
127
+ if (!duration) {
128
+ // Wait for the audio duration
129
+ duration =
130
+ (await new Promise((resolve) => {
131
+ this.onceMediaEvent('loadedmetadata', () => resolve(this.getMediaElement().duration));
132
+ })) || 0;
133
+ }
134
+ this.decodedData = Decoder.createBuffer(channelData, duration);
135
+ }
136
+ else {
137
+ // Fetch and decode the audio of no pre-computed audio data is provided
138
+ const audio = await this.fetcher.load(url);
139
+ this.decodedData = await Decoder.decode(audio);
140
+ }
141
+ this.renderAudio();
142
+ this.emit('decode', this.getDuration());
143
+ this.emit('redraw');
144
+ }
145
+ renderAudio() {
146
+ if (!this.decodedData)
147
+ return;
148
+ // Only the first two channels are used
149
+ const channelData = [this.decodedData.getChannelData(0)];
150
+ if (this.decodedData.numberOfChannels > 1) {
151
+ channelData.push(this.decodedData.getChannelData(1));
152
+ }
153
+ this.renderer.render(channelData, this.decodedData.duration);
154
+ }
155
+ /** Zoom in or out */
156
+ zoom(minPxPerSec) {
157
+ if (!this.decodedData) {
158
+ throw new Error('No audio loaded');
159
+ }
160
+ this.renderer.zoom(minPxPerSec);
161
+ this.emit('zoom', minPxPerSec);
162
+ }
163
+ /** Get the decoded audio data */
164
+ getDecodedData() {
165
+ return this.decodedData;
166
+ }
167
+ /** Get the duration of the audio in seconds */
168
+ getDuration() {
169
+ const audioDuration = super.getDuration();
170
+ return audioDuration > 0 && audioDuration < Infinity ? audioDuration : this.decodedData?.duration || 0;
171
+ }
172
+ /** Toggle if the waveform should react to clicks */
173
+ toggleInteraction(isInteractive) {
174
+ this.options.interact = isInteractive;
175
+ }
176
+ /** Seeks to a percentage of audio as [0..1] (0 = beginning, 1 = end) */
177
+ seekTo(progress) {
178
+ const time = this.getDuration() * progress;
179
+ this.setTime(time);
180
+ }
181
+ /** Play or pause the audio */
182
+ playPause() {
183
+ if (this.isPlaying()) {
184
+ this.pause();
185
+ return Promise.resolve();
186
+ }
187
+ else {
188
+ return this.play();
189
+ }
190
+ }
191
+ /** Stop the audio and go to the beginning */
192
+ stop() {
193
+ this.pause();
194
+ this.setTime(0);
195
+ }
196
+ /** Skip N or -N seconds from the current positions */
197
+ skip(seconds) {
198
+ this.setTime(this.getCurrentTime() + seconds);
199
+ }
200
+ /** Empty the waveform by loading a tiny silent audio */
201
+ empty() {
202
+ this.load('', [[0]], 0.001);
203
+ }
204
+ /** Unmount wavesurfer */
205
+ destroy() {
206
+ this.emit('destroy');
207
+ this.plugins.forEach((plugin) => plugin.destroy());
208
+ this.timer.destroy();
209
+ this.renderer.destroy();
210
+ super.destroy();
211
+ }
212
+ }
213
+ export default WaveSurfer;
@@ -1 +1 @@
1
- !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.WaveSurfer=e():t.WaveSurfer=e()}(this,(()=>(()=>{"use strict";var t={d:(e,i)=>{for(var n in i)t.o(i,n)&&!t.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:i[n]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},e={};t.d(e,{default:()=>a});const i=class{constructor(){this.eventTarget=new EventTarget}emit(t,e){const i=new CustomEvent(String(t),{detail:e});this.eventTarget.dispatchEvent(i)}on(t,e,i){const n=t=>{t instanceof CustomEvent&&e(t.detail)},s=String(t);return this.eventTarget.addEventListener(s,n,{once:i}),()=>this.eventTarget.removeEventListener(s,n)}once(t,e){return this.on(t,e,!0)}};const n=class extends i{constructor(t){super(),this.timeout=null,this.options=t;let e=null;if("string"==typeof this.options.container?e=document.querySelector(this.options.container):this.options.container instanceof HTMLElement&&(e=this.options.container),!e)throw new Error("Container not found");const i=document.createElement("div"),n=i.attachShadow({mode:"open"});n.innerHTML=`\n <style>\n :host {\n user-select: none;\n }\n :host .scroll {\n overflow-x: auto;\n overflow-y: visible;\n width: 100%;\n height: ${this.options.height}px;\n position: relative;\n }\n :host .wrapper {\n position: relative;\n width: fit-content;\n min-width: 100%;\n height: 100%;\n z-index: 2;\n }\n :host canvas {\n display: block;\n height: 100%;\n min-width: 100%;\n image-rendering: pixelated;\n }\n :host .progress {\n position: absolute;\n z-index: 2;\n top: 0;\n left: 0;\n height: 100%;\n pointer-events: none;\n clip-path: inset(100%);\n }\n :host .cursor {\n position: absolute;\n z-index: 3;\n top: 0;\n left: 0;\n height: 100%;\n border-right: 1px solid ${this.options.progressColor};\n margin-left: -1px;\n }\n </style>\n\n <div class="scroll">\n <div class="wrapper">\n <canvas></canvas>\n <canvas class="progress"></canvas>\n <div class="cursor"></div>\n </div>\n </div>\n `,this.container=i,this.scrollContainer=n.querySelector(".scroll"),this.mainCanvas=n.querySelector("canvas"),this.ctx=this.mainCanvas.getContext("2d",{desynchronized:!0}),this.progressCanvas=n.querySelector(".progress"),this.cursor=n.querySelector(".cursor"),e.appendChild(i),this.mainCanvas.addEventListener("click",(t=>{const e=this.mainCanvas.getBoundingClientRect(),i=(t.clientX-e.left)/e.width;this.emit("click",{relativeX:i})}))}getContainer(){return this.scrollContainer.querySelector(".wrapper")}destroy(){this.container.remove()}delay(t,e=100){return this.timeout&&clearTimeout(this.timeout),new Promise((i=>{this.timeout=setTimeout((()=>{i(t())}),e)}))}renderPeaks(t,e,i){var n,s,r,o,a;return s=this,r=void 0,a=function*(){const{devicePixelRatio:s}=window,{ctx:r}=this,o=null!=this.options.barWidth?this.options.barWidth*s:1,a=null!=this.options.barGap?this.options.barGap*s:this.options.barWidth?o/2:0,h=null!==(n=this.options.barRadius)&&void 0!==n?n:0,l=t[0],c=l.length,d=Math.floor(e/(o+a))/c,u=i/2,p=1===t.length,m=p?l:t[1],v=p&&m.some((t=>t<0)),y=(t,e)=>{let i=0,n=0,s=0;r.beginPath();for(let c=t;c<e;c++){const t=Math.round(c*d);if(t>i){const e=Math.round(n*u),l=Math.round(s*u);r.roundRect(i*(o+a),u-e,o,e+l||1,h),i=t,n=0,s=0}const e=v?l[c]:Math.abs(l[c]),p=v?m[c]:Math.abs(m[c]);e>n&&(n=e),(v?p<-s:p>s)&&(s=p<0?-p:p)}r.fillStyle=this.options.waveColor,r.fill(),r.closePath()};r.clearRect(0,0,e,i);const{scrollLeft:g,scrollWidth:f,clientWidth:C}=this.scrollContainer,w=c/f,b=Math.floor(g*w),x=Math.ceil((g+C)*w);y(b,x),this.createProgressMask(),b>0&&(yield this.delay((()=>{y(0,b)}))),x<c&&(yield this.delay((()=>{y(x,c)}))),this.delay((()=>{this.createProgressMask()}))},new((o=void 0)||(o=Promise))((function(t,e){function i(t){try{h(a.next(t))}catch(t){e(t)}}function n(t){try{h(a.throw(t))}catch(t){e(t)}}function h(e){var s;e.done?t(e.value):(s=e.value,s instanceof o?s:new o((function(t){t(s)}))).then(i,n)}h((a=a.apply(s,r||[])).next())}))}createProgressMask(){const t=this.progressCanvas.getContext("2d",{desynchronized:!0});this.progressCanvas.width=this.mainCanvas.width,this.progressCanvas.height=this.mainCanvas.height,this.progressCanvas.style.width=this.mainCanvas.style.width,this.progressCanvas.style.height=this.mainCanvas.style.height,t.drawImage(this.mainCanvas,0,0),t.globalCompositeOperation="source-in",t.fillStyle=this.options.progressColor,t.fillRect(0,0,this.progressCanvas.width,this.progressCanvas.height)}render(t,e){const{devicePixelRatio:i}=window,n=this.scrollContainer.clientWidth*i,s=e*this.options.minPxPerSec,r=s>n,o=r?s:n,{height:a}=this.options;this.mainCanvas.width=o,this.mainCanvas.height=a,this.mainCanvas.style.width=r?Math.round(s/i)+"px":"100%",this.renderPeaks(t,o,a)}zoom(t,e,i){const n=this.cursor.getBoundingClientRect().left;this.options.minPxPerSec=i,this.render(t,e);const s=this.cursor.getBoundingClientRect().left;this.scrollContainer.scrollLeft+=s-n}renderProgress(t,e=!1){if(this.progressCanvas.style.clipPath=`inset(0 ${100-100*t}% 0 0)`,this.cursor.style.left=100*t+"%",e){const e=this.container.clientWidth/2,i=this.mainCanvas.clientWidth;i*t>=e&&(this.scrollContainer.scrollLeft=i*t-e)}}},s=class extends i{constructor(){super(...arguments),this.unsubscribe=()=>{}}start(){this.unsubscribe=this.on("tick",(()=>{requestAnimationFrame((()=>{this.emit("tick")}))})),this.emit("tick")}stop(){this.unsubscribe()}destroy(){this.unsubscribe()}};const r={height:128,waveColor:"#999",progressColor:"#555",minPxPerSec:0};class o extends i{static create(t){return new o(t)}constructor(t){var e;super(),this.plugins=[],this.subscriptions=[],this.channelData=null,this.duration=0,this.options=Object.assign({},r,t),this.fetcher=new class{load(t){return e=this,i=void 0,s=function*(){return fetch(t).then((t=>t.arrayBuffer()))},new((n=void 0)||(n=Promise))((function(t,r){function o(t){try{h(s.next(t))}catch(t){r(t)}}function a(t){try{h(s.throw(t))}catch(t){r(t)}}function h(e){var i;e.done?t(e.value):(i=e.value,i instanceof n?i:new n((function(t){t(i)}))).then(o,a)}h((s=s.apply(e,i||[])).next())}));var e,i,n,s}},this.decoder=new class{initAudioContext(t){this.audioCtx=new AudioContext({latencyHint:"playback",sampleRate:t})}constructor(){this.audioCtx=null;try{this.initAudioContext(3e3)}catch(t){this.initAudioContext(8e3)}}decode(t){return e=this,i=void 0,s=function*(){if(!this.audioCtx)throw new Error("AudioContext is not initialized");const e=yield this.audioCtx.decodeAudioData(t),i=[e.getChannelData(0)];return e.numberOfChannels>1&&i.push(e.getChannelData(1)),{duration:e.duration,channelData:i}},new((n=void 0)||(n=Promise))((function(t,r){function o(t){try{h(s.next(t))}catch(t){r(t)}}function a(t){try{h(s.throw(t))}catch(t){r(t)}}function h(e){var i;e.done?t(e.value):(i=e.value,i instanceof n?i:new n((function(t){t(i)}))).then(o,a)}h((s=s.apply(e,i||[])).next())}));var e,i,n,s}destroy(){var t;null===(t=this.audioCtx)||void 0===t||t.close(),this.audioCtx=null}},this.timer=new s,this.player=new class{constructor({media:t,autoplay:e}){this.isExternalMedia=!1,this.hasPlayedOnce=!1,t?(this.media=t,this.isExternalMedia=!0):this.media=document.createElement("audio");const i=this.on("play",(()=>{this.hasPlayedOnce=!0,i()}));e&&(this.media.autoplay=!0)}on(t,e){var i;return null===(i=this.media)||void 0===i||i.addEventListener(t,e),()=>{var i;return null===(i=this.media)||void 0===i?void 0:i.removeEventListener(t,e)}}destroy(){var t,e;null===(t=this.media)||void 0===t||t.pause(),this.isExternalMedia||null===(e=this.media)||void 0===e||e.remove()}loadUrl(t){this.media&&(this.media.src=t)}getCurrentTime(){return this.media.currentTime}play(){this.media.play()}pause(){this.media.pause()}isPlaying(){return this.media.currentTime>0&&!this.media.paused&&!this.media.ended}seekTo(t){if(this.media){const{hasPlayedOnce:e}=this;e||this.media.play(),this.media.currentTime=t,e||this.media.pause()}}getVolume(){return this.media.volume}setVolume(t){this.media.volume=t}getMuted(){return this.media.muted}setMuted(t){this.media.muted=t}getPlaybackRate(){return this.media.playbackRate}setPlaybackRate(t,e){null!=e&&(this.media.preservesPitch=e),this.media.playbackRate=t}}({media:this.options.media,autoplay:this.options.autoplay}),this.renderer=new n({container:this.options.container,height:this.options.height,waveColor:this.options.waveColor,progressColor:this.options.progressColor,minPxPerSec:this.options.minPxPerSec,barWidth:this.options.barWidth,barGap:this.options.barGap,barRadius:this.options.barRadius}),this.initPlayerEvents(),this.initRendererEvents(),this.initTimerEvents();const i=this.options.url||(null===(e=this.options.media)||void 0===e?void 0:e.src);i&&this.load(i,this.options.channelData,this.options.duration)}initPlayerEvents(){this.subscriptions.push(this.player.on("timeupdate",(()=>{const t=this.getCurrentTime();this.renderer.renderProgress(t/this.duration,this.isPlaying()),this.emit("audioprocess",{currentTime:t})})),this.player.on("play",(()=>{this.emit("play"),this.timer.start()})),this.player.on("pause",(()=>{this.emit("pause"),this.timer.stop()})),this.player.on("canplay",(()=>{this.emit("canplay",{duration:this.getDuration()})})),this.player.on("seeking",(()=>{this.emit("seek",{time:this.getCurrentTime()})})))}initRendererEvents(){this.subscriptions.push(this.renderer.on("click",(({relativeX:t})=>{const e=this.getDuration()*t;this.seekTo(e)})))}initTimerEvents(){this.subscriptions.push(this.timer.on("tick",(()=>{const t=this.getCurrentTime();this.renderer.renderProgress(t/this.duration,!0),this.emit("audioprocess",{currentTime:t})})))}destroy(){this.subscriptions.forEach((t=>t())),this.plugins.forEach((t=>t.destroy())),this.timer.destroy(),this.player.destroy(),this.decoder.destroy(),this.renderer.destroy()}load(t,e,i){return n=this,s=void 0,o=function*(){if(this.player.loadUrl(t),null==e||null==i){const n=yield this.fetcher.load(t),s=yield this.decoder.decode(n);e=s.channelData,i=s.duration}this.channelData=e,this.duration=i,this.renderer.render(this.channelData,this.duration),this.emit("decode",{duration:this.duration})},new((r=void 0)||(r=Promise))((function(t,e){function i(t){try{h(o.next(t))}catch(t){e(t)}}function a(t){try{h(o.throw(t))}catch(t){e(t)}}function h(e){var n;e.done?t(e.value):(n=e.value,n instanceof r?n:new r((function(t){t(n)}))).then(i,a)}h((o=o.apply(n,s||[])).next())}));var n,s,r,o}zoom(t){if(null==this.channelData||null==this.duration)throw new Error("No audio loaded");this.renderer.zoom(this.channelData,this.duration,t)}play(){this.player.play()}pause(){this.player.pause()}seekTo(t){this.player.seekTo(t)}isPlaying(){return this.player.isPlaying()}getDuration(){return this.duration}getCurrentTime(){return this.player.getCurrentTime()}getVolume(){return this.player.getVolume()}setVolume(t){this.player.setVolume(t)}getMuted(){return this.player.getMuted()}setMuted(t){this.player.setMuted(t)}getPlaybackRate(){return this.player.getPlaybackRate()}setPlaybackRate(t,e){this.player.setPlaybackRate(t,e)}registerPlugin(t){const e=new t({wavesurfer:this,container:this.renderer.getContainer()});return this.plugins.push(e),e}getAudioData(){return this.channelData}}const a=o;return e.default})()));
1
+ !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.WaveSurfer=e():t.WaveSurfer=e()}(this,(()=>(()=>{"use strict";var t={d:(e,i)=>{for(var s in i)t.o(i,s)&&!t.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:i[s]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},e={};t.d(e,{default:()=>d});const i={decode:async function(t){let e;try{e=new AudioContext({sampleRate:3e3})}catch(t){e=new AudioContext({sampleRate:8e3})}const i=e.decodeAudioData(t);return i.finally((()=>e.close())),i},createBuffer:function(t,e){if("number"==typeof t[0]&&(t=[t]),t[0].some((t=>t>1||t<-1))){const e=Math.max(...t[0]);t=t.map((t=>t.map((t=>t/e))))}return{length:t[0].length,duration:e,numberOfChannels:t.length,sampleRate:t[0].length/e,getChannelData:e=>t?.[e],copyFromChannel:AudioBuffer.prototype.copyFromChannel,copyToChannel:AudioBuffer.prototype.copyToChannel}}},s=class{constructor(){this.listeners={}}on(t,e){return this.listeners[t]||(this.listeners[t]=new Set),this.listeners[t].add(e),()=>this.un(t,e)}once(t,e){const i=this.on(t,e),s=this.on(t,(()=>{i(),s()}));return i}un(t,e){this.listeners[t]&&(e?this.listeners[t].delete(e):delete this.listeners[t])}unAll(){this.listeners={}}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((t=>t(...e)))}};class n extends s{constructor(t,e){super(),this.options={height:0},this.timeout=null,this.isScrolling=!1,this.channelData=null,this.duration=null,this.resizeObserver=null,this.options={...e};let i=null;if("string"==typeof t.container?i=document.querySelector(t.container):t.container instanceof HTMLElement&&(i=t.container),!i)throw new Error("Container not found");const[s,n]=this.initHtml();i.appendChild(s),this.container=s,this.scrollContainer=n.querySelector(".scroll"),this.wrapper=n.querySelector(".wrapper"),this.canvasWrapper=n.querySelector(".canvases"),this.progressWrapper=n.querySelector(".progress"),this.wrapper.addEventListener("click",(t=>{const e=this.wrapper.getBoundingClientRect(),i=(t.clientX-e.left)/e.width;this.emit("click",i)})),this.resizeObserver=new ResizeObserver((()=>{this.delay((()=>this.reRender()),100)})),this.resizeObserver.observe(this.scrollContainer)}initHtml(){const t=document.createElement("div"),e=t.attachShadow({mode:"open"});return e.innerHTML=`\n <style>\n :host {\n user-select: none;\n }\n :host .scroll {\n overflow-x: auto;\n overflow-y: hidden;\n width: 100%;\n position: relative;\n }\n :host .noScrollbar {\n scrollbar-color: transparent;\n scrollbar-width: none;\n }\n :host .noScrollbar::-webkit-scrollbar {\n display: none;\n -webkit-appearance: none;\n }\n :host .wrapper {\n position: relative;\n overflow: visible;\n z-index: 2;\n }\n :host .canvases {\n position: relative;\n height: ${this.options.height}px;\n }\n :host canvas {\n display: block;\n position: absolute;\n top: 0;\n image-rendering: pixelated;\n height: ${this.options.height}px;\n }\n :host .progress {\n pointer-events: none;\n position: absolute;\n z-index: 2;\n top: 0;\n left: 0;\n width: 0;\n height: 100%;\n overflow: hidden;\n box-sizing: border-box;\n }\n </style>\n\n <div class="scroll">\n <div class="wrapper">\n <div class="canvases"></div>\n <div class="progress"></div>\n </div>\n </div>\n `,[t,e]}setOptions(t){this.options=t,this.reRender()}getContainer(){return this.scrollContainer}getWrapper(){return this.wrapper}destroy(){this.container.remove(),this.resizeObserver?.disconnect()}delay(t,e=10){return this.timeout&&clearTimeout(this.timeout),new Promise((i=>{this.timeout=setTimeout((()=>{i(t())}),e)}))}async renderPeaks(t,e,i,s){const r=null!=this.options.barWidth?this.options.barWidth*s:1,o=null!=this.options.barGap?this.options.barGap*s:this.options.barWidth?r/2:0,a=this.options.barRadius??0,h=this.options.barHeight??1,l=t[0],d=l.length,c=Math.floor(e/(r+o))/d,p=i/2,u=1===t.length,m=u?l:t[1],g=u&&m.some((t=>t<0)),y=(t,i)=>{let n=0,u=0,y=0;const f=document.createElement("canvas");f.width=Math.round(e*(i-t)/d),f.height=this.options.height,f.style.width=`${Math.floor(f.width/s)}px`,f.style.height=`${this.options.height}px`,f.style.left=`${Math.floor(t*e/s/d)}px`,this.canvasWrapper.appendChild(f);const v=f.getContext("2d",{desynchronized:!0});v.beginPath(),v.fillStyle=this.options.waveColor??"",v.roundRect||(v.roundRect=v.fillRect);for(let e=t;e<i;e++){const i=Math.round((e-t)*c);if(i>n){const t=Math.round(u*p*h),e=Math.round(y*p*h);v.roundRect(n*(r+o),p-t,r,t+(e||1),a),n=i,u=0,y=0}const s=g?l[e]:Math.abs(l[e]),d=g?m[e]:Math.abs(m[e]);s>u&&(u=s),(g?d<-y:d>y)&&(y=d<0?-d:d)}v.fill(),v.closePath();const b=f.cloneNode();this.progressWrapper.appendChild(b);const w=b.getContext("2d",{desynchronized:!0});f.width>0&&f.height>0&&w.drawImage(f,0,0),w.globalCompositeOperation="source-in",w.fillStyle=this.options.progressColor??"",w.fillRect(0,0,f.width,f.height)};this.canvasWrapper.innerHTML="",this.progressWrapper.innerHTML="";const{scrollLeft:f,scrollWidth:v,clientWidth:b}=this.scrollContainer,w=d/v;let C=Math.min(n.MAX_CANVAS_WIDTH,b);C-=C%((r+o)/s);const P=Math.floor(Math.abs(f)*w),M=Math.ceil(P+C*w);y(P,M);const x=M-P;for(let t=M;t<d;t+=x)await this.delay((()=>{y(t,Math.min(d,t+x))}));for(let t=P-1;t>=0;t-=x)await this.delay((()=>{y(Math.max(0,t-x),t)}))}render(t,e){const i=window.devicePixelRatio||1,s=this.scrollContainer.clientWidth,n=Math.ceil(e*(this.options.minPxPerSec||0));this.isScrolling=n>s;const r=this.options.fillParent&&!this.isScrolling,o=(r?s:n)*i,{height:a}=this.options;this.wrapper.style.width=r?"100%":`${n}px`,this.scrollContainer.style.overflowX=this.isScrolling?"auto":"hidden",this.scrollContainer.classList.toggle("noScrollbar",!!this.options.hideScrollbar),this.progressWrapper.style.borderRightStyle="solid",this.progressWrapper.style.borderRightColor=`${this.options.cursorColor||this.options.progressColor}`,this.progressWrapper.style.borderRightWidth=`${this.options.cursorWidth}px`,this.canvasWrapper.style.height=`${this.options.height}px`,this.renderPeaks(t,o,a,i),this.channelData=t,this.duration=e}reRender(){if(!this.channelData||!this.duration)return;const t=this.progressWrapper.clientWidth;this.render(this.channelData,this.duration);const e=this.progressWrapper.clientWidth;this.scrollContainer.scrollLeft+=e-t}zoom(t){this.options.minPxPerSec=t,this.reRender()}renderProgress(t,e=!1){if(!isNaN(t)&&(this.progressWrapper.style.width=100*t+"%",this.isScrolling&&this.options.autoCenter)){const{clientWidth:i,scrollLeft:s,scrollWidth:n}=this.scrollContainer,r=n*t,o=i/2,a=o/20;(r>s+(e?o:i)||r<s)&&(r-(s+o)>=a&&r<s+i?this.scrollContainer.scrollLeft+=a:this.scrollContainer.scrollLeft=r-o)}}}n.MAX_CANVAS_WIDTH=4e3;const r=n,o=class extends s{constructor(t){super(),this.subscriptions=[],this.isExternalMedia=!1,t.media?(this.media=t.media,this.isExternalMedia=!0):this.media=document.createElement("audio"),t.autoplay&&(this.media.autoplay=!0),null!=t.playbackRate&&(this.media.playbackRate=t.playbackRate)}onMediaEvent(t,e,i){return this.media.addEventListener(t,e,i),()=>this.media.removeEventListener(t,e)}onceMediaEvent(t,e){return this.onMediaEvent(t,e,{once:!0})}loadUrl(t){this.media.src=t}destroy(){this.media.pause(),this.subscriptions.forEach((t=>t())),this.isExternalMedia||this.media.remove()}play(){return this.media.play()}pause(){this.media.pause()}isPlaying(){return this.media.currentTime>0&&!this.media.paused&&!this.media.ended}setTime(t){this.media.currentTime=t}getDuration(){return this.media.duration}getCurrentTime(){return this.media.currentTime}getVolume(){return this.media.volume}setVolume(t){this.media.volume=t}getMuted(){return this.media.muted}setMuted(t){this.media.muted=t}getPlaybackRate(){return this.media.playbackRate}setPlaybackRate(t,e){null!=e&&(this.media.preservesPitch=e),this.media.playbackRate=t}getMediaElement(){return this.media}setSinkId(t){return this.media.setSinkId(t)}},a=class extends s{constructor(){super(...arguments),this.unsubscribe=()=>{}}start(){this.unsubscribe=this.on("tick",(()=>{requestAnimationFrame((()=>{this.emit("tick")}))})),this.emit("tick")}stop(){this.unsubscribe()}destroy(){this.unsubscribe()}},h={height:128,waveColor:"#999",progressColor:"#555",cursorWidth:1,minPxPerSec:0,fillParent:!0,interact:!0,autoCenter:!0};class l extends o{static create(t){return new l(t)}constructor(t){super({media:t.media,autoplay:t.autoplay,playbackRate:t.audioRate}),this.plugins=[],this.decodedData=null,this.canPlay=!1,this.options=Object.assign({},h,t),this.fetcher=new class{async load(t){return fetch(t).then((t=>t.arrayBuffer()))}},this.timer=new a,this.renderer=new r({container:this.options.container},this.options),this.initPlayerEvents(),this.initRendererEvents(),this.initTimerEvents(),this.initReadyEvent(),this.initPlugins();const e=this.options.url||this.options.media?.src;e&&this.load(e,this.options.peaks,this.options.duration)}setOptions(t){this.options={...this.options,...t},this.renderer.setOptions(this.options)}initPlayerEvents(){this.subscriptions.push(this.onMediaEvent("timeupdate",(()=>{const t=this.getCurrentTime();this.renderer.renderProgress(t/this.getDuration(),this.isPlaying()),this.emit("timeupdate",t)})),this.onMediaEvent("play",(()=>{this.emit("play"),this.timer.start()})),this.onMediaEvent("pause",(()=>{this.emit("pause"),this.timer.stop(),this.getCurrentTime()>=this.getDuration()&&this.emit("finish")})),this.onMediaEvent("canplay",(()=>{this.canPlay=!0,this.emit("canplay",this.getDuration())})),this.onMediaEvent("seeking",(()=>{this.emit("seeking",this.getCurrentTime())})))}initRendererEvents(){this.subscriptions.push(this.renderer.on("click",(t=>{this.options.interact&&(this.canPlay&&this.seekTo(t),this.emit("interaction"))})))}initTimerEvents(){this.subscriptions.push(this.timer.on("tick",(()=>{const t=this.getCurrentTime();this.renderer.renderProgress(t/this.getDuration(),!0),this.emit("timeupdate",t),this.emit("audioprocess",t)})))}initReadyEvent(){const t=()=>{this.decodedData&&this.canPlay&&this.emit("ready",this.getDuration())};this.subscriptions.push(this.on("decode",t),this.on("canplay",t))}initPlugins(){this.options.plugins?.length&&this.options.plugins.forEach((t=>{this.registerPlugin(t)}))}registerPlugin(t){return t.init({wavesurfer:this,container:this.renderer.getContainer(),wrapper:this.renderer.getWrapper()}),this.plugins.push(t),t}getActivePlugins(){return this.plugins}async load(t,e,s){if(this.decodedData=null,this.canPlay=!1,this.loadUrl(t),this.emit("load",t),e)s||(s=await new Promise((t=>{this.onceMediaEvent("loadedmetadata",(()=>t(this.getMediaElement().duration)))}))||0),this.decodedData=i.createBuffer(e,s);else{const e=await this.fetcher.load(t);this.decodedData=await i.decode(e)}this.renderAudio(),this.emit("decode",this.getDuration()),this.emit("redraw")}renderAudio(){if(!this.decodedData)return;const t=[this.decodedData.getChannelData(0)];this.decodedData.numberOfChannels>1&&t.push(this.decodedData.getChannelData(1)),this.renderer.render(t,this.decodedData.duration)}zoom(t){if(!this.decodedData)throw new Error("No audio loaded");this.renderer.zoom(t),this.emit("zoom",t)}getDecodedData(){return this.decodedData}getDuration(){const t=super.getDuration();return t>0&&t<1/0?t:this.decodedData?.duration||0}toggleInteraction(t){this.options.interact=t}seekTo(t){const e=this.getDuration()*t;this.setTime(e)}playPause(){return this.isPlaying()?(this.pause(),Promise.resolve()):this.play()}stop(){this.pause(),this.setTime(0)}skip(t){this.setTime(this.getCurrentTime()+t)}empty(){this.load("",[[0]],.001)}destroy(){this.emit("destroy"),this.plugins.forEach((t=>t.destroy())),this.timer.destroy(),this.renderer.destroy(),super.destroy()}}const d=l;return e.default})()));
package/package.json CHANGED
@@ -1,39 +1,64 @@
1
1
  {
2
2
  "name": "wavesurfer.js",
3
- "version": "7.0.0-alpha.4",
4
- "description": "wavesurfer.js is an audio library that draws waveforms and plays audio in the browser.",
5
- "main": "dist/index.js",
6
- "types": "dist/index.d.ts",
3
+ "version": "7.0.0-alpha.41",
4
+ "license": "BSD-3-Clause",
5
+ "author": "katspaugh",
6
+ "homepage": "https://wavesurfer-js.org",
7
+ "keywords": [
8
+ "waveform",
9
+ "audio",
10
+ "player",
11
+ "music",
12
+ "linguistics"
13
+ ],
14
+ "type": "module",
7
15
  "files": [
8
- "dist/"
16
+ "dist"
9
17
  ],
18
+ "types": "./dist/wavesurfer.d.ts",
19
+ "main": "./dist/wavesurfer.js",
20
+ "exports": {
21
+ ".": {
22
+ "import": "./dist/wavesurfer.js",
23
+ "require": "./dist/wavesurfer.min.js"
24
+ },
25
+ "./dist/plugins/*": {
26
+ "import": "./dist/plugins/*.js",
27
+ "require": "./dist/plugins/*.min.js"
28
+ },
29
+ "./dist/plugins/*.js": {
30
+ "import": "./dist/plugins/*.js",
31
+ "require": "./dist/plugins/*.min.js"
32
+ }
33
+ },
10
34
  "scripts": {
11
- "build": "tsc",
12
- "build:dev": "tsc -w",
13
- "build:umd": "tsc && webpack && webpack --config webpack.config.plugins.js",
14
- "prepublishOnly": "npm run build:umd",
15
- "test": "echo \"Error: no test specified\" && exit 1",
35
+ "build:dev": "tsc -w --target ESNext",
36
+ "build:umd": "webpack && webpack --config webpack.config.plugins.js",
37
+ "build": "tsc && npm run build:umd",
38
+ "deploy": "yarn build && yarn docs && rm public/dist && rm public/examples && mv dist public/ && mv examples public/",
39
+ "prepublishOnly": "npm run build",
40
+ "docs": "typedoc src/wavesurfer.ts src/plugins/* --out public/docs",
16
41
  "lint": "eslint --ext .ts src --fix",
17
- "prettier": "prettier -w src",
18
- "docs": "npx typedoc src/index.ts",
19
- "serve": "browser-sync start --server --port 9090 --startPath / --watch '*'",
42
+ "prettier": "prettier -w '**/*.{js,ts,css}' --ignore-path .gitignore",
43
+ "cypress": "cypress open",
44
+ "test": "cypress run",
45
+ "serve": "cd public && browser-sync start --server --port 9090 --watch '*' --no-ghost-mode --no-ui --cwd",
20
46
  "start": "npm run build:dev & npm run serve"
21
47
  },
22
- "author": "katspaugh <katspaugh@gmail.com>",
23
- "license": "ISC",
24
48
  "devDependencies": {
25
- "@types/react": "^18.0.28",
26
- "@typescript-eslint/eslint-plugin": "^5.54.0",
27
- "@typescript-eslint/parser": "^5.54.0",
49
+ "@typescript-eslint/eslint-plugin": "^5.57.0",
50
+ "@typescript-eslint/parser": "^5.57.0",
28
51
  "browser-sync": "^2.29.0",
29
- "eslint": "^8.35.0",
30
- "eslint-config-prettier": "^8.7.0",
52
+ "cypress": "^12.9.0",
53
+ "eslint": "^8.37.0",
54
+ "eslint-config-prettier": "^8.8.0",
31
55
  "eslint-plugin-prettier": "^4.2.1",
32
- "prettier": "^2.8.4",
56
+ "prettier": "^2.8.7",
33
57
  "ts-loader": "^9.4.2",
34
- "typedoc": "^0.23.26",
35
- "typescript": "^4.9.5",
36
- "webpack": "^5.76.1",
58
+ "typedoc": "^0.23.28",
59
+ "typedoc-plugin-rename-defaults": "^0.6.5",
60
+ "typescript": "^5.0.4",
61
+ "webpack": "^5.77.0",
37
62
  "webpack-cli": "^5.0.1"
38
63
  },
39
64
  "dependencies": {}
package/dist/index.d.ts DELETED
@@ -1,104 +0,0 @@
1
- import EventEmitter, { type GeneralEventTypes } from './event-emitter.js';
2
- import BasePlugin from './base-plugin.js';
3
- export type WaveSurferOptions = {
4
- /** HTML element or CSS selector */
5
- container: HTMLElement | string | null;
6
- /** Height of the waveform in pixels */
7
- height?: number;
8
- /** The color of the waveform */
9
- waveColor?: string;
10
- /** The color of the progress mask */
11
- progressColor?: string;
12
- /** If set, the waveform will be rendered in bars like so: ▁ ▂ ▇ ▃ ▅ ▂ */
13
- barWidth?: number;
14
- /** Spacing between bars in pixels */
15
- barGap?: number;
16
- /** Rounded borders for bars */
17
- barRadius?: number;
18
- /** Minimum pixels per second of audio (zoom) */
19
- minPxPerSec?: number;
20
- /** Audio URL */
21
- url?: string;
22
- /** Pre-computed audio data */
23
- channelData?: Float32Array[];
24
- /** Pre-computed duration */
25
- duration?: number;
26
- /** Use an existing media element instead of creating one */
27
- media?: HTMLMediaElement;
28
- /** Play the audio on load */
29
- autoplay?: boolean;
30
- };
31
- export type WaveSurferEvents = {
32
- decode: {
33
- duration: number;
34
- };
35
- canplay: {
36
- duration: number;
37
- };
38
- play: void;
39
- pause: void;
40
- audioprocess: {
41
- currentTime: number;
42
- };
43
- seek: {
44
- time: number;
45
- };
46
- };
47
- export type WaveSurferPluginParams = {
48
- wavesurfer: WaveSurfer;
49
- container: HTMLElement;
50
- };
51
- export declare class WaveSurfer extends EventEmitter<WaveSurferEvents> {
52
- private options;
53
- private fetcher;
54
- private decoder;
55
- private renderer;
56
- private player;
57
- private timer;
58
- private plugins;
59
- private subscriptions;
60
- private channelData;
61
- private duration;
62
- /** Create a new WaveSurfer instance */
63
- static create(options: WaveSurferOptions): WaveSurfer;
64
- /** Create a new WaveSurfer instance */
65
- constructor(options: WaveSurferOptions);
66
- private initPlayerEvents;
67
- private initRendererEvents;
68
- private initTimerEvents;
69
- /** Unmount wavesurfer */
70
- destroy(): void;
71
- /** Load an audio file by URL, with optional pre-decoded audio data */
72
- load(url: string, channelData?: Float32Array[], duration?: number): Promise<void>;
73
- /** Zoom in or out */
74
- zoom(minPxPerSec: number): void;
75
- /** Start playing the audio */
76
- play(): void;
77
- /** Pause the audio */
78
- pause(): void;
79
- /** Skip to a time position in seconds */
80
- seekTo(time: number): void;
81
- /** Check if the audio is playing */
82
- isPlaying(): boolean;
83
- /** Get the duration of the audio in seconds */
84
- getDuration(): number;
85
- /** Get the current audio position in seconds */
86
- getCurrentTime(): number;
87
- /** Get the audio volume */
88
- getVolume(): number;
89
- /** Set the audio volume */
90
- setVolume(volume: number): void;
91
- /** Get the audio muted state */
92
- getMuted(): boolean;
93
- /** Mute or unmute the audio */
94
- setMuted(muted: boolean): void;
95
- /** Get playback rate */
96
- getPlaybackRate(): number;
97
- /** Set playback rate, with an optional parameter to NOT preserve the pitch if false */
98
- setPlaybackRate(rate: number, preservePitch?: boolean): void;
99
- /** Register and initialize a plugin */
100
- registerPlugin<T extends BasePlugin<GeneralEventTypes>>(CustomPlugin: new (params: WaveSurferPluginParams) => T): T;
101
- /** Get the decoded audio data */
102
- getAudioData(): Float32Array[] | null;
103
- }
104
- export default WaveSurfer;
package/dist/index.js DELETED
@@ -1,188 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import Fetcher from './fetcher.js';
11
- import Decoder from './decoder.js';
12
- import Renderer from './renderer.js';
13
- import Player from './player.js';
14
- import EventEmitter from './event-emitter.js';
15
- import Timer from './timer.js';
16
- const defaultOptions = {
17
- height: 128,
18
- waveColor: '#999',
19
- progressColor: '#555',
20
- minPxPerSec: 0,
21
- };
22
- export class WaveSurfer extends EventEmitter {
23
- /** Create a new WaveSurfer instance */
24
- static create(options) {
25
- return new WaveSurfer(options);
26
- }
27
- /** Create a new WaveSurfer instance */
28
- constructor(options) {
29
- var _a;
30
- super();
31
- this.plugins = [];
32
- this.subscriptions = [];
33
- this.channelData = null;
34
- this.duration = 0;
35
- this.options = Object.assign({}, defaultOptions, options);
36
- this.fetcher = new Fetcher();
37
- this.decoder = new Decoder();
38
- this.timer = new Timer();
39
- this.player = new Player({
40
- media: this.options.media,
41
- autoplay: this.options.autoplay,
42
- });
43
- this.renderer = new Renderer({
44
- container: this.options.container,
45
- height: this.options.height,
46
- waveColor: this.options.waveColor,
47
- progressColor: this.options.progressColor,
48
- minPxPerSec: this.options.minPxPerSec,
49
- barWidth: this.options.barWidth,
50
- barGap: this.options.barGap,
51
- barRadius: this.options.barRadius,
52
- });
53
- this.initPlayerEvents();
54
- this.initRendererEvents();
55
- this.initTimerEvents();
56
- const url = this.options.url || ((_a = this.options.media) === null || _a === void 0 ? void 0 : _a.src);
57
- if (url) {
58
- this.load(url, this.options.channelData, this.options.duration);
59
- }
60
- }
61
- initPlayerEvents() {
62
- this.subscriptions.push(this.player.on('timeupdate', () => {
63
- const currentTime = this.getCurrentTime();
64
- this.renderer.renderProgress(currentTime / this.duration, this.isPlaying());
65
- this.emit('audioprocess', { currentTime });
66
- }), this.player.on('play', () => {
67
- this.emit('play');
68
- this.timer.start();
69
- }), this.player.on('pause', () => {
70
- this.emit('pause');
71
- this.timer.stop();
72
- }), this.player.on('canplay', () => {
73
- this.emit('canplay', { duration: this.getDuration() });
74
- }), this.player.on('seeking', () => {
75
- this.emit('seek', { time: this.getCurrentTime() });
76
- }));
77
- }
78
- initRendererEvents() {
79
- // Seek on click
80
- this.subscriptions.push(this.renderer.on('click', ({ relativeX }) => {
81
- const time = this.getDuration() * relativeX;
82
- this.seekTo(time);
83
- }));
84
- }
85
- initTimerEvents() {
86
- // The timer fires every 16ms for a smooth progress animation
87
- this.subscriptions.push(this.timer.on('tick', () => {
88
- const currentTime = this.getCurrentTime();
89
- this.renderer.renderProgress(currentTime / this.duration, true);
90
- this.emit('audioprocess', { currentTime });
91
- }));
92
- }
93
- /** Unmount wavesurfer */
94
- destroy() {
95
- this.subscriptions.forEach((unsubscribe) => unsubscribe());
96
- this.plugins.forEach((plugin) => plugin.destroy());
97
- this.timer.destroy();
98
- this.player.destroy();
99
- this.decoder.destroy();
100
- this.renderer.destroy();
101
- }
102
- /** Load an audio file by URL, with optional pre-decoded audio data */
103
- load(url, channelData, duration) {
104
- return __awaiter(this, void 0, void 0, function* () {
105
- this.player.loadUrl(url);
106
- // Fetch and decode the audio of no pre-computed audio data is provided
107
- if (channelData == null || duration == null) {
108
- const audio = yield this.fetcher.load(url);
109
- const data = yield this.decoder.decode(audio);
110
- channelData = data.channelData;
111
- duration = data.duration;
112
- }
113
- this.channelData = channelData;
114
- this.duration = duration;
115
- this.renderer.render(this.channelData, this.duration);
116
- this.emit('decode', { duration: this.duration });
117
- });
118
- }
119
- /** Zoom in or out */
120
- zoom(minPxPerSec) {
121
- if (this.channelData == null || this.duration == null) {
122
- throw new Error('No audio loaded');
123
- }
124
- this.renderer.zoom(this.channelData, this.duration, minPxPerSec);
125
- }
126
- /** Start playing the audio */
127
- play() {
128
- this.player.play();
129
- }
130
- /** Pause the audio */
131
- pause() {
132
- this.player.pause();
133
- }
134
- /** Skip to a time position in seconds */
135
- seekTo(time) {
136
- this.player.seekTo(time);
137
- }
138
- /** Check if the audio is playing */
139
- isPlaying() {
140
- return this.player.isPlaying();
141
- }
142
- /** Get the duration of the audio in seconds */
143
- getDuration() {
144
- return this.duration;
145
- }
146
- /** Get the current audio position in seconds */
147
- getCurrentTime() {
148
- return this.player.getCurrentTime();
149
- }
150
- /** Get the audio volume */
151
- getVolume() {
152
- return this.player.getVolume();
153
- }
154
- /** Set the audio volume */
155
- setVolume(volume) {
156
- this.player.setVolume(volume);
157
- }
158
- /** Get the audio muted state */
159
- getMuted() {
160
- return this.player.getMuted();
161
- }
162
- /** Mute or unmute the audio */
163
- setMuted(muted) {
164
- this.player.setMuted(muted);
165
- }
166
- /** Get playback rate */
167
- getPlaybackRate() {
168
- return this.player.getPlaybackRate();
169
- }
170
- /** Set playback rate, with an optional parameter to NOT preserve the pitch if false */
171
- setPlaybackRate(rate, preservePitch) {
172
- this.player.setPlaybackRate(rate, preservePitch);
173
- }
174
- /** Register and initialize a plugin */
175
- registerPlugin(CustomPlugin) {
176
- const plugin = new CustomPlugin({
177
- wavesurfer: this,
178
- container: this.renderer.getContainer(),
179
- });
180
- this.plugins.push(plugin);
181
- return plugin;
182
- }
183
- /** Get the decoded audio data */
184
- getAudioData() {
185
- return this.channelData;
186
- }
187
- }
188
- export default WaveSurfer;
@@ -1,8 +0,0 @@
1
- import Player from './player.js';
2
- declare class WebAudioPlayer extends Player {
3
- audioCtx: AudioContext | null;
4
- sourceNode: MediaElementAudioSourceNode | null;
5
- destroy(): void;
6
- loadUrl(url: string): void;
7
- }
8
- export default WebAudioPlayer;