Creating a basic rhythm game editor with HTML, CSS, and JavaScript that allows you to:
- Load audio from a URL
- Set BPM and bars count
- Play/stop audio synced to BPM
- Record notes on a timeline
- Delete notes
- Keyboard shortcuts for play/pause and record
- Share editor state via URL hash
is quite a bit of work but doable in a minimal, functional prototype.
Below is a simplified implementation:
<!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: 0; background: #222; color: #eee; }
header { padding: 1em; background: #333; display: flex; gap: 1em; flex-wrap: wrap; align-items: center; }
input[type="text"], input[type="number"] {
padding: 0.3em 0.5em;
border-radius: 3px;
border: none;
font-size: 1em;
}
button {
padding: 0.3em 0.7em;
background: #555;
color: #eee;
border: none;
border-radius: 3px;
cursor: pointer;
}
button:hover { background: #777; }
#timeline {
position: relative;
margin: 1em auto;
background: #111;
border: 1px solid #555;
width: 90vw;
height: 120px;
user-select: none;
}
#timeline .note {
position: absolute;
width: 14px;
height: 14px;
background: #4caf50;
border-radius: 3px;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
transition: background 0.2s;
}
#timeline .note.recording {
background: #ff5722;
}
#timeline .note:hover {
background: #81c784;
}
#playhead {
position: absolute;
width: 2px;
height: 100%;
background: #f44336;
pointer-events: none;
}
#info {
margin: 0 1em 1em 1em;
font-size: 0.9em;
}
#shortcuts {
font-size: 0.9em;
color: #aaa;
margin-left: auto;
}
a.share-link {
color: #4fc3f7;
text-decoration: none;
}
</style>
</head>
<body>
<header>
<label>
Audio URL:
<input id="audioUrl" type="text" size="30" placeholder="Enter audio mp3/ogg url" />
</label>
<label>
BPM:
<input id="bpm" type="number" min="20" max="300" value="120" />
</label>
<label>
Bars:
<input id="bars" type="number" min="1" max="16" value="4" />
</label>
<button id="loadAudioBtn">Load Audio</button>
<button id="playBtn" disabled>Play</button>
<button id="recordBtn" disabled>Record</button>
<button id="clearBtn">Clear Notes</button>
<a id="shareLink" class="share-link" href="#" target="_blank" title="Share link">Share</a>
<div id="shortcuts" title="Keyboard shortcuts: Space=Play/Pause, R=Record, Del=Delete note on hover">
Shortcuts: Space=Play, R=Record, Del=Delete Note
</div>
</header>
<div id="timeline" title="Click on timeline to add note">
<div id="playhead"></div>
</div>
<div id="info">Notes: 0</div>
<script>
(() => {
const audioUrlInput = document.getElementById('audioUrl');
const bpmInput = document.getElementById('bpm');
const barsInput = document.getElementById('bars');
const loadAudioBtn = document.getElementById('loadAudioBtn');
const playBtn = document.getElementById('playBtn');
const recordBtn = document.getElementById('recordBtn');
const clearBtn = document.getElementById('clearBtn');
const timeline = document.getElementById('timeline');
const playhead = document.getElementById('playhead');
const info = document.getElementById('info');
const shareLink = document.getElementById('shareLink');
let audioCtx, audioBuffer, sourceNode;
let audioElement = null;
let isPlaying = false;
let isRecording = false;
let startTime = 0;
let animationFrameRequest = null;
// Notes: stored as array of beats from 0 to total beats (bars * beats per bar)
let notes = [];
// Constants
const beatsPerBar = 4; // fixed 4/4
let bpm = 120;
let bars = 4;
// Helper for time and beat conversion
function beatToSeconds(beat) {
return (60 / bpm) * beat;
}
function secondsToBeat(sec) {
return sec / (60 / bpm);
}
// Total beats
function totalBeats() {
return bars * beatsPerBar;
}
// Load audio from URL
async function loadAudio(url) {
if(audioElement){
audioElement.pause();
audioElement.src = '';
audioElement = null;
}
audioElement = new Audio(url);
audioElement.crossOrigin = "anonymous";
await new Promise((res, rej) => {
audioElement.oncanplaythrough = () => res();
audioElement.onerror = () => rej(new Error('Failed to load audio'));
});
playBtn.disabled = false;
recordBtn.disabled = false;
}
// Play audio and sync playhead
function play() {
if(!audioElement) return;
if(isPlaying) return;
isPlaying = true;
startTime = audioElement.currentTime || 0;
audioElement.play();
playBtn.textContent = 'Pause';
animationFrameRequest = requestAnimationFrame(updatePlayhead);
}
function pause() {
if(!audioElement) return;
if(!isPlaying) return;
isPlaying = false;
audioElement.pause();
playBtn.textContent = 'Play';
if(animationFrameRequest) cancelAnimationFrame(animationFrameRequest);
}
function togglePlay(){
if(isPlaying){
pause();
} else {
play();
}
}
// Update playhead position on timeline
function updatePlayhead(){
if(!audioElement) return;
let currentTime = audioElement.currentTime;
let beat = secondsToBeat(currentTime);
// Cycle in case audio loops or extends longer
beat = beat % totalBeats();
// Calculate left % on timeline
let leftPercent = (beat / totalBeats()) * 100;
playhead.style.left = leftPercent + '%';
if(isPlaying){
animationFrameRequest = requestAnimationFrame(updatePlayhead);
}
}
// Clear all notes
function clearNotes(){
notes = [];
renderNotes();
updateInfo();
}
// Add note at beat
function addNote(beat){
// Clamp beat 0 <= beat < totalBeats
if(beat < 0) beat = 0;
if(beat >= totalBeats()) beat = totalBeats() - 0.01;
// Avoid duplicated note on almost same beat (+/-0.05)
if(notes.some(nb => Math.abs(nb - beat) < 0.05)) return false;
notes.push(beat);
notes.sort((a,b)=>a-b);
renderNotes();
updateInfo();
return true;
}
// Remove note near beat
// In this UI user deletes by hovering note and pressing Del (handled separately)
function removeNoteAtBeat(beat) {
const index = notes.findIndex(nb => Math.abs(nb - beat) < 0.05);
if(index !== -1){
notes.splice(index, 1);
renderNotes();
updateInfo();
return true;
}
return false;
}
// Render note elements on timeline
function renderNotes(){
// Remove all existing note elements except playhead
[...timeline.querySelectorAll('.note')].forEach(n => timeline.removeChild(n));
notes.forEach(beat => {
const noteEl = document.createElement('div');
noteEl.classList.add('note');
noteEl.style.left = (beat / totalBeats() * 100) + '%';
// Store beat on element dataset
noteEl.dataset.beat = beat;
timeline.appendChild(noteEl);
});
}
// Update info text
function updateInfo(){
info.textContent = `Notes: ${notes.length} | BPM: ${bpm} | Bars: ${bars}`;
}
// User clicks timeline to add note (if recording is active)
function onTimelineClick(e){
if(!isRecording) return;
const rect = timeline.getBoundingClientRect();
let x = e.clientX - rect.left;
if(x < 0) x=0;
if(x > rect.width) x=rect.width;
const pct = x / rect.width;
const beat = pct * totalBeats();
addNote(beat);
}
// Handle keyboard shortcuts
// Space = play/pause
// R = toggle record
// Delete = delete hovered note
let hoveredNote = null;
timeline.addEventListener('mousemove', e => {
if(e.target.classList.contains('note')){
hoveredNote = e.target;
hoveredNote.style.background = '#e57373';
} else if(hoveredNote){
hoveredNote.style.background = '';
hoveredNote = null;
}
});
timeline.addEventListener('mouseleave', e => {
if(hoveredNote){
hoveredNote.style.background = '';
hoveredNote = null;
}
});
window.addEventListener('keydown', e => {
if(e.target.tagName === 'INPUT') return; // ignore typing
if(e.code === 'Space'){
e.preventDefault();
togglePlay();
} else if(e.code === 'KeyR'){
e.preventDefault();
toggleRecord();
} else if(e.code === 'Delete'){
e.preventDefault();
if(hoveredNote){
const beat = parseFloat(hoveredNote.dataset.beat);
removeNoteAtBeat(beat);
}
}
});
// Toggle recording mode
function toggleRecord(){
if(!audioElement) return;
isRecording = !isRecording;
if(isRecording){
recordBtn.textContent = 'Stop Record';
recordBtn.style.background = '#ff5722';
if(!isPlaying) play();
} else {
recordBtn.textContent = 'Record';
recordBtn.style.background = '';
}
}
recordBtn.addEventListener('click', toggleRecord);
// Clicking timeline when recording adds note
timeline.addEventListener('click', onTimelineClick);
// Clear notes button
clearBtn.addEventListener('click', clearNotes);
// Load audio button
loadAudioBtn.addEventListener('click', async () => {
let val = audioUrlInput.value.trim();
if(!val) {
alert('Please enter an audio URL first.');
return;
}
try {
await loadAudio(val);
bpm = parseInt(bpmInput.value);
bars = parseInt(barsInput.value);
updateInfo();
} catch(e) {
alert('Failed to load audio: ' + e.message);
}
});
// BPM or Bars input change reflect and update info
bpmInput.addEventListener('change', () => {
bpm = parseInt(bpmInput.value) || 120;
updateInfo();
updateShareLink();
});
barsInput.addEventListener('change', () => {
bars = parseInt(barsInput.value) || 4;
updateInfo();
updateShareLink();
});
// Play button
playBtn.addEventListener('click', togglePlay);
// Updating share link based on current state: audioUrl, bpm, bars, notes
function updateShareLink(){
const state = {
audioUrl: audioUrlInput.value.trim(),
bpm,
bars,
notes
};
const encoded = encodeURIComponent(btoa(JSON.stringify(state)));
const url = location.origin + location.pathname + '#/' + encoded;
shareLink.href = url;
}
shareLink.addEventListener('click', e=>{
if(!audioUrlInput.value) {
e.preventDefault();
alert('Please load audio first to generate share link');
}
});
// When notes or inputs change, update share link
function notifyChange(){
updateShareLink();
}
bpmInput.addEventListener('input', notifyChange);
barsInput.addEventListener('input', notifyChange);
audioUrlInput.addEventListener('input', notifyChange);
// Also update share link when notes change: patch renderNotes and addNote to call notifyChange
const origAddNote = addNote;
function addNoteHook(beat){
const result = origAddNote(beat);
notifyChange();
return result;
}
addNote = addNoteHook;
const origRemoveNote = removeNoteAtBeat;
function removeNoteHook(beat){
const result = origRemoveNote(beat);
notifyChange();
return result;
}
removeNoteAtBeat = removeNoteHook;
// Load editor state from URL hash
function loadFromHash(){
const hash = location.hash;
if(hash.startsWith('#/')){
const encoded = hash.slice(2);
try {
const decoded = atob(decodeURIComponent(encoded));
const state = JSON.parse(decoded);
if(state.audioUrl) {
audioUrlInput.value = state.audioUrl;
loadAudio(state.audioUrl).then(() => {
bpm = state.bpm || 120;
bars = state.bars || 4;
notes = state.notes || [];
bpmInput.value = bpm;
barsInput.value = bars;
updateInfo();
renderNotes();
notifyChange();
}).catch(() => {
// ignore load error
});
}
} catch(e){
console.warn('Failed to load state from hash', e);
}
}
}
window.addEventListener('hashchange', loadFromHash);
loadFromHash();
updateInfo();
updateShareLink();
})();
</script>
</body>
</html>
Explanation
- Audio URL input: Load an external mp3/ogg via URL.
- BPM and Bars inputs: Control the tempo and length of the sequence.
- Play button: Plays/pauses the audio.
- Record button: When pressed, clicking on the timeline adds notes.
- Notes: Green blocks on the timeline, positioned by beat.
- Deleting notes: Hover a note then press Delete key.
- Playhead (red vertical line) moves following the audio currentTime matching the beat.
- Share link: Encodes the current state (audio URL, BPM, bars, notes) in the URL hash, so you can share a link and reload the editor state.
- Keyboard shortcuts:
- Space: play/pause
- R: start/stop recording
- Delete: delete hovered note
Usage Workflow
- Paste an audio URL and click "Load Audio".
- Adjust BPM and Bars if needed.
- Click Play to play audio.
- Click Record to enable recording.
- Click on the timeline to add notes aligned to beats.
- Hover notes and press Delete to remove.
- Click Clear Notes to remove all.
- Use the Share link to get a URL with your current pattern state.
This is a simple editor meant as a starting point—you can extend it with:
- Multiple lanes/keys notes,
- Real-time playback sync of notes (e.g. sounds for each note),
- Better UI for note selection and editing,
- Export/import JSON options.
If you want me to help implement those features too, just ask!