Skip to content

Commit 1270527

Browse files
authored
Merge pull request #524 from oshoham/p5sound-preload-bugfix
Fix bug with p5.sound AudioWorklet preload in render.js
2 parents 310f1df + 06c8d3b commit 1270527

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

src/assets/js/render.js

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,15 @@ var renderCode = function(exampleName) {
193193
'touchStarted', 'touchMoved', 'touchEnded',
194194
'keyPressed', 'keyReleased', 'keyTyped'];
195195
var _found = [];
196+
// p.preload is an empty function created by the p5.sound library in order to use the p5.js preload system
197+
// to load AudioWorklet modules before a sketch runs, even if that sketch doesn't have its own preload function.
198+
// However, this causes an error in the eval code below because the _found array will always contain "preload",
199+
// even if the sketch in question doesn't have a preload function. To get around this, we delete p.preload before
200+
// eval-ing the sketch and add it back afterwards if the sketch doesn't contain its own preload function.
201+
// For more info, see: https://github.com/processing/p5.js-sound/blob/master/src/audioWorklet/index.js#L22
202+
if (p.preload) {
203+
delete p.preload;
204+
}
196205
with (p) {
197206
// Builds a function to detect declared functions via
198207
// them being hoisted past the return statement. Does
@@ -220,8 +229,9 @@ var renderCode = function(exampleName) {
220229
].join('\n'));
221230
}
222231
// If we haven't found any functions we'll assume it's
223-
// just a setup body.
232+
// just a setup body with an empty preload.
224233
if (!_found.length) {
234+
p.preload = function() {};
225235
p.setup = function() {
226236
p.createCanvas(100, 100);
227237
p.background(200);
@@ -237,10 +247,12 @@ var renderCode = function(exampleName) {
237247
_found.forEach(function(name) {
238248
p[name] = eval(name);
239249
});
250+
// Ensure p.preload exists even if the sketch doesn't have a preload function.
251+
p.preload = p.preload || function() {};
240252
p.setup = p.setup || function() {
241253
p.createCanvas(100, 100);
242254
p.background(200);
243-
}
255+
};
244256
}
245257
};
246258
}

0 commit comments

Comments
 (0)