Skip to content

Commit a3a7e4b

Browse files
authored
fix: fix position jump on playback rate change (#4268)
* fix: fix position jump on playback rate change * refacor: rename field
1 parent 729107c commit a3a7e4b

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

src/webaudio.ts

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ class WebAudioPlayer extends EventEmitter<WebAudioPlayerEvents> {
2424
private gainNode: GainNode
2525
private bufferNode: AudioBufferSourceNode | null = null
2626
private playStartTime = 0
27-
private playedDuration = 0
27+
private playbackPosition = 0
2828
private _muted = false
2929
private _playbackRate = 1
3030
private _duration: number | undefined = undefined
@@ -110,10 +110,10 @@ class WebAudioPlayer extends EventEmitter<WebAudioPlayerEvents> {
110110
this.bufferNode.playbackRate.value = this._playbackRate
111111
this.bufferNode.connect(this.gainNode)
112112

113-
let currentPos = this.playedDuration * this._playbackRate
113+
let currentPos = this.playbackPosition
114114
if (currentPos >= this.duration || currentPos < 0) {
115115
currentPos = 0
116-
this.playedDuration = 0
116+
this.playbackPosition = 0
117117
}
118118

119119
this.bufferNode.start(this.audioContext.currentTime, currentPos)
@@ -130,7 +130,7 @@ class WebAudioPlayer extends EventEmitter<WebAudioPlayerEvents> {
130130
private _pause() {
131131
this.paused = true
132132
this.bufferNode?.stop()
133-
this.playedDuration += this.audioContext.currentTime - this.playStartTime
133+
this.playbackPosition += (this.audioContext.currentTime - this.playStartTime) * this._playbackRate
134134
}
135135

136136
async play() {
@@ -171,23 +171,26 @@ class WebAudioPlayer extends EventEmitter<WebAudioPlayerEvents> {
171171
return this._playbackRate
172172
}
173173
set playbackRate(value) {
174+
const wasPlaying = !this.paused
175+
if (wasPlaying) this._pause()
174176
this._playbackRate = value
177+
if (wasPlaying) this._play()
178+
175179
if (this.bufferNode) {
176180
this.bufferNode.playbackRate.value = value
177181
}
178182
}
179183

180184
get currentTime() {
181-
const time = this.paused
182-
? this.playedDuration
183-
: this.playedDuration + (this.audioContext.currentTime - this.playStartTime)
184-
return time * this._playbackRate
185+
return this.paused
186+
? this.playbackPosition
187+
: this.playbackPosition + (this.audioContext.currentTime - this.playStartTime) * this._playbackRate
185188
}
186189
set currentTime(value) {
187190
const wasPlaying = !this.paused
188191

189192
if (wasPlaying) this._pause()
190-
this.playedDuration = value / this._playbackRate
193+
this.playbackPosition = value
191194
if (wasPlaying) this._play()
192195

193196
this.emit('seeking')

0 commit comments

Comments
 (0)