Got it! You want to create a rhythm game editor implemented in HTML/CSS/JS with the following features:
- Load audio from a URL
- Play the audio track
- Allow recording of notes (probably by hitting keys)
- Display bars and count rhythm (musical timing)
- Keyboard shortcuts (for control: play, record, delete notes, etc)
- Delete notes
- Share (probably export data or URL)
- Use hash based routing or state (
#/) for sharing or navigation
Below is a starting point — a minimal but functional rhythm game editor that covers these basics:
- You can input an audio URL to load a track
- Play / pause the audio
- Visual beat/bar counter with a simple grid of notes (per bar)
- Use keyboard shortcuts to add/delete notes (e.g. pressing keys to add)
- Record notes as you play
- Visualize notes in a simple timeline / bar grid
- Share data is exported to URL hash (JSON encoded)
- Load from URL hash on page load for sharing
Demo 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: Arial, sans-serif;
margin: 1rem;
background: #222;
color: #eee;
}
#controls {
margin-bottom: 1rem;
}
input[type="text"] {
width: 300px;
}
button {
margin-left: 0.5rem;
padding: 0.5rem 1rem;
background: #0a74da;
border: none;
color: #fff;
cursor: pointer;
}
button:disabled {
background: #555;
cursor: default;
}
#track-bar {
margin-top: 1rem;
background: #333;
height: 120px;
overflow-x: auto;
white-space: nowrap;
border: 1px solid #555;
}
.bar {
display: inline-block;
vertical-align: top;
width: 320px;
border-right: 1px solid #555;
position: relative;
height: 120px;
}
.bar-number {
position: absolute;
top: 5px;
left: 5px;
font-size: 12px;
color: #aaa;
}
.note-row {
display: flex;
height: 20px;
border-top: 1px solid #444;
}
.note-cell {
flex: 1;
border-left: 1px solid #444;
cursor: pointer;
user-select: none;
position: relative;
}
.note-cell.note {
background: #0a74da;
}
.note-cell.played {
background: #4caf50;
}
#info {
margin-top: 1rem;
font-size: 14px;
line-height: 1.5;
color: #ccc;
}
</style>
</head>
<body>
<h1>Rhythm Game Editor</h1>
<div id="controls">
<input id="audio-url" type="text" placeholder="Enter audio URL here" />
<button id="load-audio">Load Audio</button>
<button id="play-pause" disabled>Play</button>
<button id="record" disabled>Start Recording</button>
<button id="delete-all" disabled>Delete All Notes</button>
<button id="share" disabled>Share (copy link)</button>
</div>
<div id="track-bar" tabindex="0"></div>
<div id="info">
<b>Instructions:</b><br />
- Load an audio URL.<br/>
- Press Play to start the audio.<br/>
- Press Record and hit keys 1-4 to add notes.<br/>
- Click notes to delete.<br />
- Use LEFT/RIGHT arrows to move song cursor.<br/>
- Press DELETE to remove selected note.<br />
- Use the Share button to copy editor state as URL hash.<br/>
</div>
<script>
(() => {
// Constants
const NOTES = 4; // number of rows (lanes)
const BARS = 8; // number of bars initially
const BEATS_PER_BAR = 4; // beats per bar
const SUBDIVISION = 4; // subdivisions per beat (16th notes)
// Calculated total cells per bar
const CELLS_PER_BAR = BEATS_PER_BAR * SUBDIVISION;
// State
let audio = null;
let audioURL = '';
let playing = false;
let recording = false;
let startTime = 0;
let notes = []; // array of { time: seconds, lane:0-3, bar, cell }
let animationFrameId = null;
let selectedNote = null;
// Audio context for timing reference
let audioCtx = new (window.AudioContext || window.webkitAudioContext)();
let audioSource = null;
// Elements
const audioUrlInput = document.getElementById('audio-url');
const loadButton = document.getElementById('load-audio');
const playPauseBtn = document.getElementById('play-pause');
const recordBtn = document.getElementById('record');
const deleteAllBtn = document.getElementById('delete-all');
const shareBtn = document.getElementById('share');
const trackBar = document.getElementById('track-bar');
// Timing info
const bpm = 120; // Default BPM
const beatDuration = 60 / bpm; // seconds per beat
const barDuration = beatDuration * BEATS_PER_BAR;
// Utility: get bar, cell for a time (seconds)
function timeToBarCell(timeSec) {
const totalCells = (timeSec / barDuration) * CELLS_PER_BAR;
const bar = Math.floor(totalCells / CELLS_PER_BAR);
const cell = Math.floor(totalCells % CELLS_PER_BAR);
return { bar, cell };
}
// Utility: get time for bar + cell
function barCellToTime(bar, cell) {
return (bar + cell / CELLS_PER_BAR) * barDuration;
}
// Load audio from URL
loadButton.onclick = () => {
const url = audioUrlInput.value.trim();
if (!url) return alert('Please enter an audio URL');
loadAudio(url);
};
async function loadAudio(url) {
if (audio) {
audio.pause();
audio = null;
playPauseBtn.disabled = true;
recordBtn.disabled = true;
deleteAllBtn.disabled = true;
shareBtn.disabled = true;
notes = [];
selectedNote = null;
cancelAnimation();
renderTimeline();
console.log('Previous audio stopped.');
}
try {
audio = new Audio(url);
audio.crossOrigin = "anonymous";
await audio.play().then(() => audio.pause()); // preload & get metadata
audioURL = url;
playPauseBtn.disabled = false;
recordBtn.disabled = false;
deleteAllBtn.disabled = false;
shareBtn.disabled = false;
playing = false;
playPauseBtn.textContent = 'Play';
notes = [];
selectedNote = null;
cancelAnimation();
renderTimeline();
updateShareHash();
console.log('Audio loaded:', url);
} catch (e) {
alert('Error loading audio: ' + e.message);
console.error(e);
}
}
// Play / Pause toggle
playPauseBtn.onclick = () => {
if (!audio) return;
if (playing) {
pauseAudio();
} else {
playAudio();
}
};
function playAudio() {
if (!audio) return;
audio.play();
playing = true;
playPauseBtn.textContent = 'Pause';
if (recording) {
startTime = audio.currentTime;
}
animationFrameId = requestAnimationFrame(update);
}
function pauseAudio() {
if (!audio) return;
audio.pause();
playing = false;
playPauseBtn.textContent = 'Play';
cancelAnimation();
}
function cancelAnimation() {
if (animationFrameId) {
cancelAnimationFrame(animationFrameId);
animationFrameId = null;
}
}
// Recording toggle
recordBtn.onclick = () => {
if (!audio) return;
if (recording) {
recording = false;
recordBtn.textContent = 'Start Recording';
} else {
// Can start recording only if playing
if (!playing) {
alert('Play audio first!');
return;
}
recording = true;
recordBtn.textContent = 'Stop Recording';
startTime = audio.currentTime;
}
};
// Keyboard input for recording notes & navigation
window.addEventListener('keydown', e => {
if (!audio) return;
if (recording) {
const key = e.key;
// keys 1-4 for lanes
if (key >= '1' && key <= '4') {
const lane = Number(key) - 1;
const time = audio.currentTime;
addNote(time, lane);
e.preventDefault();
}
}
switch (e.key) {
case 'ArrowRight':
if (audio) {
audio.currentTime = Math.min(audio.duration, audio.currentTime + 1);
update();
}
break;
case 'ArrowLeft':
if (audio) {
audio.currentTime = Math.max(0, audio.currentTime - 1);
update();
}
break;
case 'Delete':
if (selectedNote != null) {
notes = notes.filter(n => n !== selectedNote);
selectedNote = null;
renderTimeline();
updateShareHash();
}
break;
}
});
// Add a note at a time and lane
function addNote(time, lane) {
let {bar, cell} = timeToBarCell(time);
if (bar >= BARS) {
// extend bars?
console.log('Note beyond visible bars, ignoring');
return;
}
notes.push({ time, lane, bar, cell });
renderTimeline();
updateShareHash();
}
// Render the timeline bars and notes
function renderTimeline() {
trackBar.innerHTML = '';
for (let b = 0; b < BARS; b++) {
const barDiv = document.createElement('div');
barDiv.className = 'bar';
barDiv.dataset.bar = b;
const barNumber = document.createElement('div');
barNumber.className = 'bar-number';
barNumber.textContent = `Bar ${b+1}`;
barDiv.appendChild(barNumber);
for (let lane = 0; lane < NOTES; lane++) {
const noteRow = document.createElement('div');
noteRow.className = 'note-row';
for (let c = 0; c < CELLS_PER_BAR; c++) {
const cell = document.createElement('div');
cell.className = 'note-cell';
cell.dataset.bar = b;
cell.dataset.cell = c;
cell.dataset.lane = lane;
// Check if note exists here
let noteHere = notes.find(n => n.bar === b && n.cell === c && n.lane === lane);
if (noteHere) {
cell.classList.add('note');
if (noteHere === selectedNote) cell.classList.add('played');
}
// Click toggle note
cell.onclick = (ev) => {
const foundNote = notes.find(n => n.bar == b && n.cell == c && n.lane == lane);
if (foundNote) {
if (selectedNote === foundNote) selectedNote = null;
else selectedNote = foundNote;
} else {
// Add note on click if not exists
if (!recording) {
const t = barCellToTime(b,c);
addNote(t,lane);
selectedNote = notes[notes.length-1];
}
}
renderTimeline();
};
noteRow.appendChild(cell);
}
barDiv.appendChild(noteRow);
}
trackBar.appendChild(barDiv);
}
}
// Update the timeline highlighting based on audio current time
function update() {
if (!audio || !playing) return;
const currentTime = audio.currentTime;
// highlight notes near currentTime (within a quarter beat)
const threshold = beatDuration / 4;
// clear all played highlights
[...trackBar.querySelectorAll('.note-cell.played')].forEach(cell => cell.classList.remove('played'));
// highlight current notes
notes.forEach(n => {
if (Math.abs(n.time - currentTime) < threshold) {
// mark as played
const selector = `.note-cell.note[data-bar="${n.bar}"][data-cell="${n.cell}"][data-lane="${n.lane}"]`;
const cell = trackBar.querySelector(selector);
if (cell) cell.classList.add('played');
}
});
animationFrameId = requestAnimationFrame(update);
}
// Delete all notes
deleteAllBtn.onclick = () => {
if (!confirm('Delete all notes?')) return;
notes = [];
selectedNote = null;
renderTimeline();
updateShareHash();
};
// Share: copy link to clipboard with state encoded in hash
shareBtn.onclick = () => {
updateShareHash(true);
};
// Encode notes and audioURL into URL hash
function updateShareHash(copyToClipboard = false) {
const exportData = {
audio: audioURL,
notes: notes.map(({bar, cell, lane})=> ({bar, cell, lane}))
};
const str = btoa(JSON.stringify(exportData));
const url = window.location.origin + window.location.pathname + '#/' + str;
window.history.replaceState(null, '', url);
if (copyToClipboard) {
navigator.clipboard.writeText(url).then(() => {
alert('Link copied to clipboard!');
}, () => {
alert('Failed to copy link.');
});
}
}
// On page load - load from hash if present
function loadFromHash() {
if (!window.location.hash.startsWith('#/')) return;
const enc = window.location.hash.slice(2);
try {
const json = atob(enc);
const data = JSON.parse(json);
if (data.audio) {
audioUrlInput.value = data.audio;
loadAudio(data.audio).then(() => {
if (data.notes) {
notes = data.notes;
renderTimeline();
}
});
}
} catch(e) {
console.error('Failed to load hash data', e);
}
}
loadFromHash();
})();
</script>
</body>
</html>
Features in this demo:
- Load audio by URL input, supports cross-origin audio files (CORS required).
- Basic play/pause audio control.
- 8 bars of 4 beats per bar with 16 subdivisions each.
- 4 lanes (rows), user can add notes by pressing number keys 1-4 during recording.
- Press "Start Recording" then play audio and hit keys 1-4 to add notes that snap to nearest subdivision.
- Notes are visual boxes on a grid to represent time (bar+cell) and lane.
- Notes can be clicked to select; press DELETE key removes the selected note.
- Arrow keys Left/Right let you jump audio position.
- Delete All removes all notes.
- Share button serializes audio URL + notes into base64 in URL hash to share with others.
- On page load, if URL contains hash, automatically loads audio and note data.
How to use:
- Find a publicly hosted mp3 that supports CORS (e.g. your own server or a hosted mp3 file).
- Paste its URL in input box and click Load Audio.
- Wait until loaded, then press Play.
- Press Start Recording button and then press 1-4 keys along the music to record note timing and lane.
- Press Stop Recording when done.
- You can select notes by clicking and press DELETE key to remove.
- Click Share to copy a URL with your data, then open it in a new tab or share with friends.
What you can build on this:
- Implement BPM/time signature input and dynamically adjust bars.
- More refined snapping options (e.g. 8th notes, triplets).
- Visualize a playhead cursor moving along bars.
- Export/import notes from JSON file.
- Sounds or haptic feedback on note hit.
- More UI polish and responsive layout.
If you want, I can also help you modularize the code or add more advanced features!