Skip to content

Commit

Permalink
docs(example): update audio example making it funier (#496)
Browse files Browse the repository at this point in the history
  • Loading branch information
lajbel committed Nov 1, 2024
1 parent feb64df commit b1a4c4b
Showing 1 changed file with 61 additions and 23 deletions.
84 changes: 61 additions & 23 deletions examples/audio.js
Original file line number Diff line number Diff line change
@@ -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);
Expand All @@ -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";

Expand All @@ -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();
}

0 comments on commit b1a4c4b

Please sign in to comment.