Tone.js/examples/animationSync.html
2020-07-18 17:20:19 -07:00

94 lines
2.7 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Analyser</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="icon" type="image/png" sizes="174x174" href="./favicon.png">
<script src="https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/2.4.3/webcomponents-bundle.js"></script>
<link href="https://fonts.googleapis.com/css?family=Material+Icons&display=block" rel="stylesheet"/>
<script src="../build/Tone.js"></script>
<script src="./js/tone-ui.js"></script>
<script src="./js/components.js"></script>
</head>
<body>
<style type="text/css">
#Notes{
width: 100%;
height: 20px;
position: relative;
margin-bottom: 10px;
}
.Note {
width: 20%;
height: 100%;
position: relative;
float: left;
background-color: black;
opacity: 0;
transition: opacity 0.5s;
}
.Note.active {
opacity: 1;
transition-duration: 0.1s;
}
</style>
<tone-example label="Synchronizing Visuals">
<div slot="explanation">
Audio scheduling and rendering visuals should always be kept separate. Instead of triggering visuals from within a scheduled event callback, schedule a 'deferred' callback using Tone.Draw which will be invoked on an animation frame at the exact moment of the scheduled event.
<br><br>
For more information see <a href="https://github.com/Tonejs/Tone.js/wiki/Performance">this wiki article</a>.
</div>
<div id="content">
<div id="Notes">
<div id="C4" class="Note"></div>
<div id="E4" class="Note"></div>
<div id="G4" class="Note"></div>
<div id="B4" class="Note"></div>
<div id="D5" class="Note"></div>
</div>
<tone-play-toggle></tone-play-toggle>
</div>
</tone-example>
<script type="text/javascript">
const piano = new Tone.Synth({
oscillator: {
type: "fmsine4",
modulationType: "square"
}
}).toDestination();
const loop = new Tone.Pattern(((time, note) => {
piano.triggerAttackRelease(note, "16n", time);
// Draw.schedule takes a callback and a time to invoke the callback
Tone.Draw.schedule(() => {
// the callback synced to the animation frame at the given time
const noteElement = document.querySelector("#"+note);
noteElement.classList.add("active");
setTimeout(() => {
noteElement.classList.remove("active");
}, 100);
}, time);
}), ["C4", "E4", "G4", "B4", "D5"]).start(0);
loop.interval = "16n";
Tone.Transport.lookAhead = 0.5;
drawer().add({
tone: piano,
title: "Piano",
});
// connect the UI with the components
document.querySelector("tone-play-toggle").addEventListener("start", () => Tone.Transport.start());
document.querySelector("tone-play-toggle").addEventListener("stop", () => Tone.Transport.stop());
</script>
</body>
</html>