It sounds like you want to create a rhythm game editor in HTML/CSS/JS with these features:
- Load an audio from a URL
- Play notes in sync with the audio
- Record notes input by the user
- Support for measures (bars) and beats count
- Display rhythm visually
- Keyboard shortcuts for adding/deleting notes
- Ability to delete notes
- Share or export the created rhythm pattern
- Use URL hash (
#/) for sharing/loading patterns from URL
Below I'll provide a minimal but extensible starter template with key features you can build upon. It includes:
- Audio loading from URL input
- Simple grid representing bars and beats, allowing note placement by clicking or using keyboard shortcuts
- Playback synced with audio using
AudioContext for precise timing
- Simple record mode to capture user inputs as notes
- Export/import pattern via URL hash
Full Example Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Rhythm Game Editor</title>
<style>
body {
font-family: sans-serif;
margin: 20px;
background: #121212;
color: #eee;
}
header {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
}
input[type=url], input[type=number] {
width: 100%;
max-width: 600px;
padding: 6px;
font-size: 1em;
margin-bottom: 10px;
}
button {
font-size: 1em;
padding: 6px 12px;
margin-right: 10px;
}
#grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(25px, 1fr));
gap: 4px;
max-width: 700px;
margin-top: 20px;
}
.beat {
width: 25px;
height: 25px;
background: #222;
border-radius: 4px;
cursor: pointer;
user-select: none;
transition: background-color 0.2s;
}
.beat.active {
background: #1db954;
}
.beat.playing {
border: 2px solid #1db954;
}
#status {
margin-top: 10px;
height: 20px;
}
#shortcuts {
margin-top: 20px;
max-width: 600px;
font-size: 0.85em;
}
#audio-player {
max-width: 600px;
width: 100%;
outline: none;
}
</style>
</head>
<body>
<header>
<label for="audio-url">Load Audio URL:</label>
<input type="url" id="audio-url" placeholder="Paste audio URL here (mp3, ogg, wav...)" />
<button id="load-audio">Load Audio</button>
</header>
<div>
<label for="bars-count">Bars (measures):</label>
<input type="number" id="bars-count" value="4" min="1" max="64" />
<label for="beats-per-bar">Beats per Bar:</label>
<input type="number" id="beats-per-bar" value="4" min="1" max="16" />
</div>
<div>
<button id="play-btn" disabled>Play</button>
<button id="stop-btn" disabled>Stop</button>
<button id="record-btn" disabled>Record</button>
<button id="delete-btn" disabled>Delete Selected Note</button>
<button id="share-btn">Get Share Link</button>
</div>
<div id="status"></div>
<div id="grid" tabindex="0" aria-label="Rhythm editor grid"></div>
<div id="shortcuts">
<strong>Shortcuts:</strong><br/>
Select note: Click beat box<br/>
Add note: Spacebar<br/>
Delete note: Delete key<br/>
Play/Pause: P key<br/>
Record: R key<br/>
</div>
<audio id="audio-player" controls crossorigin="anonymous"></audio>
<script>
(() => {
const audioUrlInput = document.getElementById('audio-url');
const loadAudioBtn = document.getElementById('load-audio');
const playBtn = document.getElementById('play-btn');
const stopBtn = document.getElementById('stop-btn');
const recordBtn = document.getElementById('record-btn');
const deleteBtn = document.getElementById('delete-btn');
const shareBtn = document.getElementById('share-btn');
const audioPlayer = document.getElementById('audio-player');
const gridEl = document.getElementById('grid');
const statusEl = document.getElementById('status');
const barsCountInput = document.getElementById('bars-count');
const beatsPerBarInput = document.getElementById('beats-per-bar');
let bars = parseInt(barsCountInput.value, 10);
let beatsPerBar = parseInt(beatsPerBarInput.value, 10);
let totalBeats = bars * beatsPerBar;
let notes = new Set(); // store beat indexes where notes are placed
let selectedBeat = null;
let isPlaying = false;
let isRecording = false;
let playbackStartTime = 0;
let scheduledTimeouts = [];
// We use Web Audio API for better timing control
let audioContext = null;
let audioBuffer = null;
let sourceNode = null;
function updateGrid() {
gridEl.innerHTML = '';
totalBeats = bars * beatsPerBar;
gridEl.style.gridTemplateColumns = `repeat(${beatsPerBar}, 25px)`;
for(let i = 0; i < totalBeats; i++) {
const beatBox = document.createElement('div');
beatBox.className = 'beat';
beatBox.dataset.beat = i;
if(notes.has(i)) beatBox.classList.add('active');
if(selectedBeat === i) beatBox.classList.add('selected');
gridEl.appendChild(beatBox);
}
}
function setStatus(text = '') {
statusEl.textContent = text;
}
// Load audio from URL using Web Audio API
async function loadAudio(url) {
try {
setStatus('Loading audio...');
if(!audioContext) audioContext = new (window.AudioContext || window.webkitAudioContext)();
const response = await fetch(url);
if(!response.ok) throw new Error(`HTTP error: ${response.status}`);
const arrayBuffer = await response.arrayBuffer();
audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
audioPlayer.src = url; // For the HTML audio controls as fallback
playBtn.disabled = false;
stopBtn.disabled = true;
recordBtn.disabled = false;
deleteBtn.disabled = notes.size === 0;
setStatus('Audio loaded!');
// Reset player if playing
if(isPlaying) stopPlayback();
} catch(e) {
setStatus('Failed to load audio: ' + e.message);
console.error(e);
}
}
function playNoteSoundAt(beatIndex) {
if(!audioContext || !audioBuffer) return;
// For simplicity, we just play a small chunk/short sound here.
// To keep it simple, you might want to play a short beep or the entire audio.
}
function playPlayback() {
if(isPlaying || !audioBuffer) return;
isPlaying = true;
setStatus('Playing...');
playBtn.disabled = true;
stopBtn.disabled = false;
// Start AudioContext or resume
if(audioContext.state === 'suspended') {
audioContext.resume();
}
sourceNode = audioContext.createBufferSource();
sourceNode.buffer = audioBuffer;
sourceNode.connect(audioContext.destination);
playbackStartTime = audioContext.currentTime;
sourceNode.start();
// Schedule note highlights
scheduleNoteHighlights();
sourceNode.onended = () => {
stopPlayback();
};
}
function stopPlayback() {
if(!isPlaying) return;
isPlaying = false;
setStatus('Stopped.');
playBtn.disabled = false;
stopBtn.disabled = true;
if(sourceNode) {
try {
sourceNode.stop();
} catch(e) {}
sourceNode.disconnect();
sourceNode = null;
}
clearScheduledTimeouts();
clearPlayingHighlights();
}
function clearScheduledTimeouts() {
scheduledTimeouts.forEach(t => clearTimeout(t));
scheduledTimeouts = [];
}
function clearPlayingHighlights() {
document.querySelectorAll('.beat.playing').forEach(el=>{
el.classList.remove('playing');
});
}
function scheduleNoteHighlights() {
clearScheduledTimeouts();
// We'll schedule highlight for all notes according to audio duration and beats count.
// Let's assume uniform beat duration = audio duration / total beats
const duration = audioBuffer.duration;
const beatDuration = duration / totalBeats;
notes.forEach(beatIndex => {
if(beatIndex >= totalBeats) return;
const timeoutId = setTimeout(() => {
highlightBeat(beatIndex);
}, beatDuration * beatIndex * 1000);
scheduledTimeouts.push(timeoutId);
});
// Also schedule clearing highlight per beat + scheduled next beat
for(let i=0; i < totalBeats; i++) {
const timeoutId = setTimeout(() => {
clearPlayingHighlights();
}, beatDuration * (i + 0.2) * 1000);
scheduledTimeouts.push(timeoutId);
}
}
function highlightBeat(beatIndex) {
clearPlayingHighlights();
const beatEl = gridEl.querySelector(`.beat[data-beat='${beatIndex}']`);
if(beatEl) {
beatEl.classList.add('playing');
}
}
// Toggle note at beat index
function toggleNote(beatIndex) {
if(notes.has(beatIndex)) {
notes.delete(beatIndex);
} else {
notes.add(beatIndex);
}
updateGrid();
deleteBtn.disabled = notes.size === 0;
}
// Delete selected note if any
function deleteSelectedNote() {
if(selectedBeat !== null && notes.has(selectedBeat)) {
notes.delete(selectedBeat);
updateGrid();
deleteBtn.disabled = notes.size === 0;
setStatus(`Deleted note at beat ${selectedBeat+1}`);
}
}
// Record mode: enabled/disabled
function setRecordingMode(enabled) {
isRecording = enabled;
recordBtn.textContent = enabled ? 'Stop Recording' : 'Record';
setStatus(enabled ? 'Recording... Press notes to add.' : 'Recording stopped.');
}
// Add note during record mode at clicked or pressed beat
function addNoteDuringRecord(beatIndex) {
notes.add(beatIndex);
updateGrid();
}
// Export pattern as compact string for URL
function exportPattern() {
// Serialize into string like "bars=4&beats=4¬es=1,3,5,10"
let data = {
bars: bars,
beats: beatsPerBar,
notes: Array.from(notes).sort((a,b) => a-b)
};
return encodeURIComponent(JSON.stringify(data));
}
// Import pattern from string
function importPattern(dataStr) {
try {
const data = JSON.parse(decodeURIComponent(dataStr));
if(data.bars && data.beats && Array.isArray(data.notes)) {
bars = data.bars;
beatsPerBar = data.beats;
barsCountInput.value = bars;
beatsPerBarInput.value = beatsPerBar;
totalBeats = bars * beatsPerBar;
notes = new Set(data.notes.filter(i => i < totalBeats));
selectedBeat = null;
updateGrid();
deleteBtn.disabled = notes.size === 0;
setStatus('Pattern loaded from URL.');
}
} catch(e) {
setStatus('Invalid pattern data in URL.');
}
}
// Load pattern from URL hash if present
function loadFromHash() {
if(location.hash.startsWith('#/')) {
const dataStr = location.hash.slice(2);
importPattern(dataStr);
}
}
// Set share link with current pattern encoded in URL hash
function setShareLink() {
const patternStr = exportPattern();
const shareURL = `${location.origin}${location.pathname}#/${patternStr}`;
navigator.clipboard.writeText(shareURL)
.then(() => setStatus('Share link copied to clipboard!'))
.catch(() => setStatus('Failed to copy share link.'));
}
// Event Listeners
loadAudioBtn.addEventListener('click', () => {
if(audioUrlInput.value.trim()) {
loadAudio(audioUrlInput.value.trim());
}
});
playBtn.addEventListener('click', () => {
playPlayback();
});
stopBtn.addEventListener('click', () => {
stopPlayback();
});
recordBtn.addEventListener('click', () => {
if(!isRecording) {
setRecordingMode(true);
} else {
setRecordingMode(false);
}
});
deleteBtn.addEventListener('click', () => {
deleteSelectedNote();
});
shareBtn.addEventListener('click', () => {
setShareLink();
});
barsCountInput.addEventListener('change', () => {
let val = parseInt(barsCountInput.value, 10);
if(val < 1) barsCountInput.value = val=1;
if(val > 64) barsCountInput.value = val=64;
bars = val;
totalBeats = bars * beatsPerBar;
// Remove notes too large to fit
notes = new Set(Array.from(notes).filter(i => i < totalBeats));
updateGrid();
});
beatsPerBarInput.addEventListener('change', () => {
let val = parseInt(beatsPerBarInput.value, 10);
if(val < 1) beatsPerBarInput.value = val=1;
if(val > 16) beatsPerBarInput.value = val=16;
beatsPerBar = val;
totalBeats = bars * beatsPerBar;
notes = new Set(Array.from(notes).filter(i => i < totalBeats));
updateGrid();
});
// Grid click to select/toggle note
gridEl.addEventListener('click', e => {
if(e.target.classList.contains('beat')) {
const beatIndex = parseInt(e.target.dataset.beat, 10);
selectedBeat = beatIndex;
if(isRecording) {
addNoteDuringRecord(beatIndex);
} else {
// Just select the beat box on click
updateGrid();
setStatus(`Selected beat ${beatIndex+1}`);
deleteBtn.disabled = !notes.has(beatIndex);
}
}
});
// Keyboard shortcuts
window.addEventListener('keydown', e => {
if(document.activeElement === audioUrlInput) return; // Ignore when typing in URL input
if(document.activeElement === barsCountInput) return;
if(document.activeElement === beatsPerBarInput) return;
switch(e.key) {
case ' ': // Spacebar to toggle note on selected beat
e.preventDefault();
if(selectedBeat !== null) {
toggleNote(selectedBeat);
setStatus(`Toggled note at beat ${selectedBeat+1}`);
deleteBtn.disabled = !notes.has(selectedBeat);
}
break;
case 'Delete': // Delete note at selected beat
e.preventDefault();
deleteSelectedNote();
break;
case 'p': // Play/pause toggle
case 'P':
e.preventDefault();
if(isPlaying) stopPlayback();
else playPlayback();
break;
case 'r': // Record toggle
case 'R':
e.preventDefault();
setRecordingMode(!isRecording);
break;
case 'ArrowRight':
e.preventDefault();
if(selectedBeat === null) selectedBeat = 0;
else if(selectedBeat < totalBeats - 1) selectedBeat++;
updateGrid();
setStatus(`Selected beat ${selectedBeat+1}`);
deleteBtn.disabled = !notes.has(selectedBeat);
break;
case 'ArrowLeft':
e.preventDefault();
if(selectedBeat === null) selectedBeat = 0;
else if(selectedBeat > 0) selectedBeat--;
updateGrid();
setStatus(`Selected beat ${selectedBeat+1}`);
deleteBtn.disabled = !notes.has(selectedBeat);
break;
}
});
// Initialization
updateGrid();
loadFromHash();
})();
</script>
</body>
</html>
How To Use
- Paste an audio URL (mp3, wav, ogg) and click Load Audio.
- Set your desired number of bars (measures) and beats per bar.
- Click on the grid boxes ("beats") to select a beat.
- Use Spacebar to toggle a note on / off at the selected beat.
- Use arrow keys left/right to move selection.
- The notes appear green squares.
- Press P to play or stop playback of the audio and see note highlights synced.
- Press R to toggle recording mode. In record mode, clicking beats will add notes.
- Press Delete to delete the selected note.
- Click Get Share Link to copy a URL with the current pattern encoded in the hash.
- You can share or reload the page with a pattern link, which loads the pattern automatically.
Possible Improvements (for your future development)
- Use Web Audio API oscillator or samples for note sounds.
- Visualize time/progress bar.
- Support multiple note types/instruments.
- Import/export as JSON file.
- Zoom or scroll grid for larger beat counts.
- Drag & drop to move notes.
- Visual beat/bar lines for easier rhythm understanding.
- Better mobile support.
- Use requestAnimationFrame for smoother animation over timeout scheduling.
- Sync with the actual audio's time update and adjust for latency.
This starter should help you get going with your rhythm game editor! Let me know if you'd like help adding features or improving things.