Creating a rhythm game editor with features like BPM setting, loading audio via URL, play note, record rhythm, bars count, shortcuts for delete, and share functionality using HTML, CSS, and JavaScript is a moderately complex task that can be broken down step-by-step.
html Copy 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:0; padding:0; background: #121212; color: #eee;
}
header {
padding: 10px;
background: #222;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
}
label {
font-weight: bold;
margin-right: 4px;
}
input, button {
font-size: 1rem;
padding: 4px 8px;
border-radius: 4px;
border: none;
}
input[type="text"] {
width: 400px;
}
button {
cursor: pointer;
background: #4caf50;
color: #fff;
border: none;
}
button:hover {
background: #45a049;
}
#timelineContainer {
margin-top: 10px;
position: relative;
overflow-x: auto;
white-space: nowrap;
border-top: 2px solid #444;
border-bottom: 2px solid #444;
user-select: none;
background: #222;
}
#timeline {
height: 120px;
position: relative;
display: inline-block; /* so width based on bars */
}
.bar {
display: inline-block;
width: 320px; /* 4 beats * 80px per beat */
border-right: 1px solid #555;
position: relative;
vertical-align: top;
height: 100%;
}
.beat {
position: absolute;
top: 0;
height: 100%;
width: 80px;
border-left: 1px solid #555;
}
.note {
position: absolute;
bottom: 10px;
width: 18px;
height: 18px;
background: #ff4081;
border-radius: 4px;
cursor: pointer;
transition: transform 0.1s;
}
.note.selected {
transform: scale(1.4);
box-shadow: 0 0 8px #ff80ab;
}
#playhead {
position: absolute;
top: 0;
width: 2px;
background: #00e676;
height: 100%;
pointer-events: none;
z-index: 10;
}
#status {
margin-left: auto;
font-weight: bold;
font-size: 1.1rem;
}
#shareLink {
width: 80vw;
margin: 6px 12px;
padding: 6px 8px;
background: #333;
color: #eee;
font-family: monospace;
font-size: 0.9rem;
border-radius: 4px;
outline: none;
}
#controls {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
}
</style>
</head>
<body>
<header>
<div id="controls">
<label for="audioUrl">Audio URL:</label>
<input type="text" id="audioUrl" placeholder="Paste audio file URL here" autocomplete="off" />
<button id="loadAudioBtn">Load</button>
<label for="bpm">BPM:</label>
<input type="number" id="bpm" min="30" max="300" value="120" />
<label for="bars">Bars:</label>
<input type="number" id="bars" min="1" max="32" value="8" />
<button id="playBtn">Play</button>
<button id="pauseBtn" disabled>Pause</button>
<button id="recordBtn">Record (Space)</button>
<button id="clearBtn">Clear Notes</button>
</div>
<div id="status">Stopped</div>
</header>
<div id="timelineContainer">
<div id="timeline"></div>
<div id="playhead"></div>
</div>
<section style="padding:10px;">
<label for="shareLink">Share Link:</label><br>
<input id="shareLink" readonly />
</section>
<script>
(() => {
// Constants
const beatsPerBar = 4;
const beatWidthPx = 80;
// State
let bpm = 120;
let bars = 8;
let audio = null;
let audioContext = null;
let audioSource = null;
let startTime = 0;
let isPlaying = false;
let playRequestId = null;
let notes = []; // Array of {bar, beat} objects for simplicity, extended to fractional beats for more precision
let selectedNotes = new Set();
let isRecording = false;
// Elements
const audioUrlInput = document.getElementById('audioUrl');
const loadAudioBtn = document.getElementById('loadAudioBtn');
const bpmInput = document.getElementById('bpm');
const barsInput = document.getElementById('bars');
const playBtn = document.getElementById('playBtn');
const pauseBtn = document.getElementById('pauseBtn');
const recordBtn = document.getElementById('recordBtn');
const clearBtn = document.getElementById('clearBtn');
const timeline = document.getElementById('timeline');
const timelineContainer = document.getElementById('timelineContainer');
const playhead = document.getElementById('playhead');
const statusEl = document.getElementById('status');
const shareLinkInput = document.getElementById('shareLink');
// Utilities: serialize notes and state into URL hash for share
function encodeShare() {
// Data structure:
// bpm,bars;base64(notes)
// notes: each note encoded as bar*100 + beat*10 as two digit integers separated by ','
// We use decimal with 1 digit beat precision (0-3.9 beats)
const notesStr = notes.map(n => {
// Encode as bar*100 + beat*10, e.g. bar=2, beat=1.5 -> 2*100 + 15 = 215
const val = n.bar * 100 + Math.round(n.beat * 10);
return val.toString(36); // base36 small string
}).join(',');
const stateStr = `b${bpm}b${bars}n${notesStr}`;
const encoded = btoa(stateStr);
location.hash = encoded;
shareLinkInput.value = location.href;
}
function decodeShare() {
try {
const hash = location.hash.substring(1);
if (!hash) return;
const decoded = atob(hash);
// Parse our state string - b{bpm}b{bars}n{notes}
const bpmMatch = decoded.match(/b(\d+)/);
const barsMatch = decoded.match(/b(\d+)n/);
const notesMatch = decoded.match(/n(.+)/);
if (bpmMatch) bpmInput.value = bpm = parseInt(bpmMatch[1],10);
if (barsMatch) barsInput.value = bars = parseInt(barsMatch[1],10);
if (notesMatch) {
const noteStr = notesMatch[1];
if(noteStr.length > 0) {
notes = noteStr.split(',').map(s => {
const val = parseInt(s,36);
const bar = Math.floor(val / 100);
const beat = (val % 100)/10;
return {bar,beat};
});
}
} else {
notes = [];
}
renderTimeline();
} catch(e) {
// fail silently ignore bad data
notes = [];
}
}
// Render the timeline grid per bars and notes
function renderTimeline() {
timeline.innerHTML = '';
timeline.style.width = bars * beatsPerBar * beatWidthPx + 'px';
for(let b=0; b<bars;b++) {
const barEl = document.createElement('div');
barEl.className = 'bar';
// Add vertical lines for beats inside bar
for(let beat=1; beat < beatsPerBar; beat++) {
const beatEl = document.createElement('div');
beatEl.className = 'beat';
beatEl.style.left = (beat * beatWidthPx) + 'px';
barEl.appendChild(beatEl);
}
timeline.appendChild(barEl);
}
// Render notes
notes.forEach((note,i) => {
const noteEl = document.createElement('div');
noteEl.className = 'note';
noteEl.style.left = ((note.bar * beatsPerBar + note.beat) * beatWidthPx - 9) + 'px'; // center note on beat, 18/2=9
noteEl.title = `Bar ${note.bar+1}, Beat ${note.beat.toFixed(2)}`;
noteEl.tabIndex = 0;
// Click select toggle
noteEl.addEventListener('click', e => {
if(selectedNotes.has(i)) {
selectedNotes.delete(i);
noteEl.classList.remove('selected');
} else {
selectedNotes.add(i);
noteEl.classList.add('selected');
}
updateStatus();
});
timeline.appendChild(noteEl);
// Store element ref for selection highlight
note.el = noteEl;
});
positionPlayhead(0);
updateStatus();
}
// Update status text
function updateStatus(msg) {
if(msg) {
statusEl.textContent = msg;
} else {
if (isPlaying) {
statusEl.textContent = `Playing - BPM:${bpm} Bars:${bars} Notes:${notes.length} Selected:${selectedNotes.size}`;
} else if (isRecording) {
statusEl.textContent = 'Recording... (Press Space to stop)';
} else {
statusEl.textContent = `Stopped - BPM:${bpm} Bars:${bars} Notes:${notes.length}`;
}
}
}
// Setup Web Audio playback to sync playhead and audio
async function setupAudio(url) {
if(audioSource) {
audioSource.disconnect();
audioSource = null;
}
if(audio) {
audio.pause();
audio.currentTime = 0;
}
if(audioContext) {
try { await audioContext.close(); } catch(e){}
}
audioContext = new AudioContext();
audio = new Audio();
audio.crossOrigin = "anonymous";
audio.src = url;
return new Promise((resolve,reject)=>{
audio.addEventListener('canplaythrough', () => {
resolve(audio);
});
audio.addEventListener('error', e => {
reject(e);
});
});
}
function playAudio() {
if(!audio) return;
if(audioContext.state === 'suspended') {
audioContext.resume();
}
audio.play();
startTime = audioContext.currentTime - audio.currentTime;
isPlaying = true;
updateStatus();
playhead.style.display = 'block';
playRequestId = requestAnimationFrame(updatePlayhead);
}
function pauseAudio() {
if(!audio) return;
audio.pause();
isPlaying = false;
updateStatus();
cancelAnimationFrame(playRequestId);
playRequestId = null;
}
function stopAudio() {
if(!audio) return;
audio.pause();
audio.currentTime = 0;
isPlaying = false;
updateStatus();
cancelAnimationFrame(playRequestId);
playRequestId = null;
positionPlayhead(0);
}
// Update playhead position in pixels according to audio currentTime
function updatePlayhead() {
if(!isPlaying || !audio) return;
let currentTime = audio.currentTime;
let beatDuration = 60 / bpm;
const beatsPassed = currentTime / beatDuration;
// Clamp max to timeline length
const maxBeats = bars * beatsPerBar;
const clampedBeats = Math.min(beatsPassed, maxBeats);
// Position playhead
positionPlayhead(clampedBeats * beatWidthPx);
// Playback finished
if(currentTime >= audio.duration) {
pauseAudio();
stopAudio();
return;
}
// If recording, capture pressed keys as notes
if(isRecording && lastSpacePressed) {
recordCurrentNote(beatsPassed);
}
playRequestId = requestAnimationFrame(updatePlayhead);
}
// Set playhead CSS left in pixels
function positionPlayhead(x) {
const timelineRect = timeline.getBoundingClientRect();
playhead.style.left = x + 'px';
// Autoscroll timeline to keep playhead visible
const containerRect = timelineContainer.getBoundingClientRect();
const relativeX = x - timelineContainer.scrollLeft;
if(relativeX < 50) {
timelineContainer.scrollLeft = Math.max(0, timelineContainer.scrollLeft - 50);
} else if(relativeX > containerRect.width - 50) {
timelineContainer.scrollLeft = Math.min(timeline.scrollWidth - containerRect.width, timelineContainer.scrollLeft + 50);
}
}
// Mouse click on timeline adds note at clicked beat
timelineContainer.addEventListener('click', e => {
if (e.target === playhead) return; // ignore clicks on playhead
const rect = timeline.getBoundingClientRect();
const x = e.clientX - rect.left + timelineContainer.scrollLeft;
let beatPos = x / beatWidthPx;
beatPos = Math.min(beatPos, bars * beatsPerBar - 0.1);
// Snap beat to nearest 0.1 for precision
const bar = Math.floor(beatPos / beatsPerBar);
const beat = +(beatPos % beatsPerBar).toFixed(1);
notes.push({bar,beat});
renderTimeline();
encodeShare();
});
// Keyboard shortcuts
window.addEventListener('keydown', e => {
if(e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return; // Ignore inputs
if(e.key === 'Delete' || e.key === 'Backspace') {
// Delete selected notes
if(selectedNotes.size > 0) {
notes = notes.filter((_,i) => !selectedNotes.has(i));
selectedNotes.clear();
renderTimeline();
encodeShare();
e.preventDefault();
}
}
else if(e.key === ' ') {
e.preventDefault();
toggleRecord();
}
});
// Record notes as spacebar pressed while playing
let lastSpacePressed = false;
function toggleRecord() {
if (!audio || !isPlaying) {
updateStatus('Play audio before recording');
return;
}
isRecording = !isRecording;
if(isRecording) {
statusEl.textContent = 'Recording... (Press Space to stop)';
lastSpacePressed = true;
} else {
statusEl.textContent = `Stopped recording. BPM:${bpm} Bars:${bars} Notes:${notes.length}`;
}
}
function recordCurrentNote(beatsPassed) {
// Only add note once per space key press to avoid flooding notes
if(!lastSpacePressed) return;
lastSpacePressed = false;
// Calculate bar and beat with precision
const totalBeats = beatsPassed;
if(totalBeats > bars * beatsPerBar) return; // outside range
const bar = Math.floor(totalBeats / beatsPerBar);
const beat = +(totalBeats % beatsPerBar).toFixed(1);
notes.push({bar,beat});
renderTimeline();
encodeShare();
}
// Event handlers for UI controls
loadAudioBtn.addEventListener('click', async () => {
const url = audioUrlInput.value.trim();
if(!url) {
alert('Please enter a valid audio URL');
return;
}
try {
statusEl.textContent = 'Loading audio...';
await setupAudio(url);
statusEl.textContent = 'Loaded audio. Ready to play.';
stopAudio();
encodeShare();
} catch(e) {
alert('Failed to load audio. Check the URL and CORS policy.');
statusEl.textContent = 'Failed to load audio.';
}
});
bpmInput.addEventListener('change', e => {
const val = +bpmInput.value;
if(val >= 30 && val <= 300) {
bpm = val;
renderTimeline();
encodeShare();
}
});
barsInput.addEventListener('change', e => {
const val = +barsInput.value;
if(val >= 1 && val <= 32 ) {
bars = val;
renderTimeline();
encodeShare();
}
});
playBtn.addEventListener('click', () => {
if(!audio) {
alert('Please load audio first.');
return;
}
playAudio();
playBtn.disabled = true;
pauseBtn.disabled = false;
});
pauseBtn.addEventListener('click', () => {
pauseAudio();
playBtn.disabled = false;
pauseBtn.disabled = true;
});
recordBtn.addEventListener('click', () => {
toggleRecord();
});
clearBtn.addEventListener('click', () => {
if(confirm('Clear all notes?')) {
notes = [];
selectedNotes.clear();
renderTimeline();
encodeShare();
}
});
// Clipboard share link select all on focus
shareLinkInput.addEventListener('focus', () => {
shareLinkInput.select();
});
// Initial render
decodeShare();
renderTimeline();
// If hash contains saved state, shareLinkInput shows it
if(location.hash.length > 1) {
shareLinkInput.value = location.href;
}
})();
</script>
</body>
</html>
If you want me to build out any particular part more fully or add features, just ask!