<div id="tapBar" class="mb-4">
Tap here to make music!
</div>
<div class="button-group">
<button id="playButton" class="action-button">Play Sequence</button>
<button id="clearButton" class="action-button">Clear Sequence</button>
</div>
<div id="messageBox"></div>
</div>
<script>
// Ensure Tone.js is loaded before proceeding
if (typeof Tone === 'undefined') {
console.error("Tone.js is not loaded. Please check the CDN link.");
}
// Initialize Tone.js components
let synth; // Our synthesizer
let recordedSequence = []; // Stores objects like { note: 'C4', time: 0.5 }
let startTime = 0; // To keep track of the start time of recording
// DOM elements
const <REDACTED> = <REDACTED>');
const playButton = document.getElementById('playButton');
const clearButton = document.getElementById('clearButton');
const messageBox = document.getElementById('messageBox');
/**
* Displays a message in the message box.
* @param {string} message - The message to display.
* @param {number} duration - How long to show the message in milliseconds.
*/
function showMessage(message, duration = 2000) {
messageBox.textContent = message;
messageBox.classList.add('show');
<REDACTED>(() => {
messageBox.classList.remove('show');
}, duration);
}
/**
* Initializes the audio context and synthesizer.
* This function is called on the first user interaction to comply with browser autoplay policies.
*/
async function initializeAudio() {
if (Tone.context.state !== 'running') {
await Tone.start();
console.log('Audio context started');
}
// Create a simple polyphonic synthesizer
synth = new Tone.PolySynth(Tone.Synth, {
oscillator: {
type: "sine" // A smooth sine wave
},
envelope: {
attack: 0.005,
decay: 0.1,
sustain: 0.3,
release: 1
}
}).toDestination(); // Connect to the speakers
console.log('Synthesizer initialized');
}
/**
* Generates a random musical note.
* @returns {string} A note string (e.g., 'C4', 'D#3').
*/
function getRandomNote() {
const notes = ['C', 'D', 'E', 'F', 'G', 'A', 'B'];
const accidentals = ['', '#', 'b']; // Natural, sharp, flat
const octaves = [3, 4, 5]; // Common musical octaves
const randomNote = notes[Math.floor(Math.random() * notes.length)];
const randomAccidental = accidentals[Math.floor(Math.random() * accidentals.length)];
const randomOctave = <REDACTED>() * octaves.length)];
return `${randomNote}${randomAccidental}${randomOctave}`;
}
/**
* Handles the tap event on the bar.
* Plays a random note and records it.
*/
async function handleTap() {
// Initialize audio on first tap
if (!synth) {
await initializeAudio();
}
// If this is the first tap, set the recording start time
if (recordedSequence.length === 0) {
startTime = Tone.now();
showMessage("Recording started!");
}
const note = getRandomNote();
const tapTime = Tone.now();
const relativeTime = tapTime - startTime; // Time relative to the start of recording
// Play the note immediately
synth.triggerAttackRelease(note, '8n'); // Play for an 8th note duration
// Record the note and its relative time
recordedSequence.push({ note: note, time: relativeTime });
console.log(`Tapped: ${note} at relative time: ${relativeTime.toFixed(2)}s`);
showMessage(`Note: ${note}`);
}
/**
* Handles the play button click.
* Plays back the recorded sequence.
*/
async function handlePlay() {
if (!synth) {
showMessage("Tap the bar first to record a sequence!");
return;
}
if (recordedSequence.length === 0) {
showMessage("No sequence recorded. Tap the bar to create one!");
return;
}
showMessage("Playing sequence...");
console.log("Playing sequence:", recordedSequence);
// Stop any ongoing playback
Tone.Transport.stop();
Tone.Transport.cancel(); // Clear all scheduled events
// Schedule each note in the sequence
<URL>rEach(item => {
Tone.Transport.scheduleOnce(() => {
synth.triggerAttackRelease(item.note, '8n');
console.log(`Playing: ${item.note} at Transport time: ${Tone.Transport.seconds.toFixed(2)}s`);
}, item.time);
});
// Start the transport
Tone.Transport.start();
// Optional: Show message when playback finishes
const totalDuration = recordedSequence.reduce((max, item) => Math.max(max, item.time), 0) + 1; // Add a bit for release
<REDACTED>(() => {
showMessage("Playback finished.");
}, totalDuration * 1000); // Convert Tone.js seconds to milliseconds
}
/**
* Handles the clear button click.
* Clears the recorded sequence and resets the start time.
*/
function handleClear() {
recordedSequence = [];
startTime = 0;
Tone.Transport.stop();
Tone.Transport.cancel();
showMessage("Sequence cleared!");
console.log("Sequence cleared.");
}
// Event Listeners for tap and buttons
tapBar.addEventListener('click', handleTap);
playButton.addEventListener('click', handlePlay);
clearButton.addEventListener('click', handleClear);
// Add touch event listeners for mobile devices
tapBar.addEventListener('touchstart', (e) => {
e.preventDefault(); // Prevent scrolling/zooming
handleTap();
});
playButton.addEventListener('touchstart', (e) => {
e.preventDefault();
handlePlay();
});
clearButton.addEventListener('touchstart', (e) => {
e.preventDefault();
handleClear();
});
// Initial message
window.onload = () => {
showMessage("Tap the bar to start recording your tune!");
};
</script>