Skip to content

Commit

Permalink
Feat: add error event (#3532)
Browse files Browse the repository at this point in the history
* add error event

* Update src/wavesurfer.ts

* catch decode error
  • Loading branch information
zachkrall authored Mar 9, 2024
1 parent e32e519 commit e389ed8
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
24 changes: 24 additions & 0 deletions cypress/e2e/error.cy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
describe('WaveSurfer error handling tests', () => {
it('should fire error event if provided file url does not exist', () => {
cy.visit('cypress/e2e/index.html')

cy.window().its('WaveSurfer').should('exist')

cy.window().then((win) => {
return new Promise((resolve, reject) => {
win.wavesurfer = win.WaveSurfer.create({
container: '#waveform',
height: 200,
waveColor: 'rgb(200, 200, 0)',
progressColor: 'rgb(100, 100, 0)',
url: '../../examples/audio/DOES_NOT_EXIST.wav',
})

win.wavesurfer.on('error', () => {
console.log('error event fired')
resolve()
})
})
})
})
})
20 changes: 20 additions & 0 deletions src/wavesurfer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,8 @@ export type WaveSurferEvents = {
zoom: [minPxPerSec: number]
/** Just before the waveform is destroyed so you can clean up your events */
destroy: []
/** When source file is unable to be fetched, decoded, or an error is thrown by media element */
error: []
}

class WaveSurfer extends Player<WaveSurferEvents> {
Expand Down Expand Up @@ -241,6 +243,10 @@ class WaveSurfer extends Player<WaveSurferEvents> {
this.onMediaEvent('seeking', () => {
this.emit('seeking', this.getCurrentTime())
}),

this.onMediaEvent('error', () => {
this.emit('error')
}),
)
}

Expand Down Expand Up @@ -386,6 +392,15 @@ class WaveSurfer extends Player<WaveSurferEvents> {
if (!blob && !channelData) {
const onProgress = (percentage: number) => this.emit('loading', percentage)
blob = await Fetcher.fetchBlob(url, onProgress, this.options.fetchParams)
.then((blob) => blob)
.catch(() => {
this.emit('error')
return undefined
})
}

if (!blob) {
return
}

// Set the mediaelement source
Expand Down Expand Up @@ -413,6 +428,11 @@ class WaveSurfer extends Player<WaveSurferEvents> {
} else if (blob) {
const arrayBuffer = await blob.arrayBuffer()
this.decodedData = await Decoder.decode(arrayBuffer, this.options.sampleRate)
.then((buffer) => buffer)
.catch(() => {
this.emit('error')
return null
})
}

if (this.decodedData) {
Expand Down

0 comments on commit e389ed8

Please sign in to comment.