Skip to content

Commit de83cd8

Browse files
authored
Merge pull request #728 from processing/fix/distorted-sound
Reuse SoundFile's worklet node to prevent distortion
2 parents aeba38a + ad9a856 commit de83cd8

File tree

1 file changed

+24
-25
lines changed

1 file changed

+24
-25
lines changed

src/soundfile.js

Lines changed: 24 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1362,40 +1362,39 @@ class SoundFile {
13621362
var now = ac.currentTime;
13631363
var cNode = ac.createBufferSource();
13641364

1365-
const workletBufferSize = safeBufferSize(256);
1366-
1367-
// dispose of worklet node if it already exists
1368-
if (self._workletNode) {
1369-
self._workletNode.disconnect();
1370-
delete self._workletNode;
1371-
}
1372-
self._workletNode = new AudioWorkletNode(
1373-
ac,
1374-
processorNames.soundFileProcessor,
1375-
{
1376-
processorOptions: { bufferSize: workletBufferSize },
1377-
}
1378-
);
1379-
self._workletNode.port.onmessage = (event) => {
1380-
if (event.data.name === 'position') {
1381-
// event.data.position should only be 0 when paused
1382-
if (event.data.position === 0) {
1383-
return;
1365+
// Reuse the worklet node rather than creating a new one. Even if we
1366+
// disconnect it, it seems to leak and cause choppy audio after a
1367+
// while.
1368+
if (!self._workletNode) {
1369+
const workletBufferSize = safeBufferSize(256);
1370+
self._workletNode = new AudioWorkletNode(
1371+
ac,
1372+
processorNames.soundFileProcessor,
1373+
{
1374+
processorOptions: { bufferSize: workletBufferSize },
13841375
}
1385-
this._lastPos = event.data.position;
1376+
);
1377+
self._workletNode.port.onmessage = (event) => {
1378+
if (event.data.name === 'position') {
1379+
// event.data.position should only be 0 when paused
1380+
if (event.data.position === 0) {
1381+
return;
1382+
}
1383+
this._lastPos = event.data.position;
13861384

1387-
// do any callbacks that have been scheduled
1388-
this._onTimeUpdate(self._lastPos);
1389-
}
1390-
};
1385+
// do any callbacks that have been scheduled
1386+
this._onTimeUpdate(self._lastPos);
1387+
}
1388+
};
1389+
self._workletNode.connect(p5.soundOut._silentNode);
1390+
}
13911391

13921392
// create counter buffer of the same length as self.buffer
13931393
cNode.buffer = _createCounterBuffer(self.buffer);
13941394

13951395
cNode.playbackRate.setValueAtTime(self.playbackRate, now);
13961396

13971397
cNode.connect(self._workletNode);
1398-
self._workletNode.connect(p5.soundOut._silentNode);
13991398

14001399
return cNode;
14011400
}

0 commit comments

Comments
 (0)