diff --git a/examples/audio.js b/examples/audio.js index 580c99a9..b0710800 100644 --- a/examples/audio.js +++ b/examples/audio.js @@ -1,48 +1,55 @@ // @ts-check - -// audio playback & control +// Playing audio and controlling it kaplay({ // This makes it so the audio doesn't pause when the tab is changed backgroundAudio: true, - background: [0, 0, 0], + background: "5ba675", }); -// Loads the bell sound, and OtherworldlyFoe sound +// Loads the bell sound loadSound("bell", "/examples/sounds/bell.mp3"); +// Load the music, it makes it being streamed, so loading is faster loadMusic("OtherworldlyFoe", "/examples/sounds/OtherworldlyFoe.mp3"); +loadSprite("bag", "/sprites/bag.png"); + +// Adjust global volume +volume(0.5); + +// We use the play() function to play audio +onKeyPress("enter", () => { + play("bell", { + volume: 1, + speed: 1, + }); +}); + +// For our mobile friends +onTouchStart(() => { + play("bell", { + volume: 1, + speed: 1, + }); +}); -// play() to play audio -// (This might not play until user input due to browser policy) +// We can also play music, and control it const music = play("OtherworldlyFoe", { loop: true, paused: true, }); -// Adjust global volume -volume(0.5); - const label = add([ text(), + pos(10, 10), ]); -function updateText() { - label.text = ` -${music.paused ? "Paused" : "Playing"} -Time: ${music.time().toFixed(2)} -Volume: ${music.volume.toFixed(2)} -Speed: ${music.speed.toFixed(2)} - -\\[space] play/pause -[up/down] volume -[left/right] speed - `.trim(); -} - +// See below for the function updateText(); // Update text every frame -onUpdate(updateText); +onUpdate(() => { + updateText(); +}); // Adjust music properties through input onKeyPress("space", () => music.paused = !music.paused); @@ -52,6 +59,7 @@ onKeyPressRepeat("left", () => music.speed -= 0.1); onKeyPressRepeat("right", () => music.speed += 0.1); onKeyPress("m", () => music.seek(4.24)); +// Piano // We store some keys in a string const keyboard = "awsedftgyhujk"; @@ -75,3 +83,33 @@ onDraw(() => { height: h, }); }); + +// The rotating bag +const bag = add([ + sprite("bag"), + pos(center()), + anchor("center"), + rotate(0), + scale(2), +]); + +bag.onUpdate(() => { + if (music.paused) return; + + bag.angle += dt() * 100; +}); + +// Create text guide +function updateText() { + label.text = ` +${music.paused ? "Paused" : "Playing"} +Time: ${music.time().toFixed(2)} +Volume: ${music.volume.toFixed(2)} +Speed: ${music.speed.toFixed(2)} + +\\[space] play/pause +[up/down] volume +[left/right] speed +[a...k] piano + `.trim(); +}