Creating a random sheet music generator in HTML, CSS, and JavaScript that includes bars, seed-based randomness, time signature, rhythm, and keys can be quite involved but definitely doable. Below is an example of a simple implementation that demonstrates:
html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Random Sheet Music Generator</title>
<style>
body {
font-family: sans-serif;
padding: 1em;
background: #f0f0f0;
}
#controls > * {
margin: 0.5em 0.5em 1em 0;
}
#sheet {
background: white;
padding: 1em;
border-radius: 8px;
box-shadow: 0 0 15px rgba(0,0,0,0.1);
overflow-x: auto;
white-space: nowrap;
}
</style>
</head>
<body>
<h1>Random Sheet Music Generator</h1>
<div id="controls">
<label>
Seed:
<input type="text" id="seedInput" value="12345" />
</label>
<label>
Time Signature:
<select id="timeSig">
<option value="4/4" selected>4/4</option>
<option value="3/4">3/4</option>
<option value="6/8">6/8</option>
<option value="2/4">2/4</option>
</select>
</label>
<label>
Key Signature:
<select id="keySig">
<option value="C" selected>C</option>
<option value="G">G</option>
<option value="D">D</option>
<option value="A">A</option>
<option value="E">E</option>
<option value="F">F</option>
<option value="Bb">Bb</option>
</select>
</label>
<label>
Number of Bars:
<input type="number" id="numBars" min="1" max="16" value="4" />
</label>
<button id="generateBtn">Generate</button>
</div>
<div id="sheet"></div>
<!-- VexFlow Library -->
<script src="https://unpkg.com/vexflow/releases/vexflow-min.js"></script>
<script>
// Simple seeded random number generator (Mulberry32)
function mulberry32(seed) {
return function() {
var t = seed += 0x6D2B79F5;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
}
// Helper: parse time signature string "4/4" to {num:4, denom:4}
function parseTimeSig(ts) {
let [num, denom] = ts.split('/').map(Number);
return {num, denom};
}
// Available note durations and their duration in beats (based on denominator=4)
// For example, in 4/4: quarter note = 1 beat, half note = 2 beats, whole =4 beats
// We interpret duration string for VexFlow as: 4 = quarter, 8 = eighth, 2=half, 1=whole
const noteDurations = [
{duration: "w", beats: 4}, // whole note
{duration: "h", beats: 2}, // half note
{duration: "q", beats: 1}, // quarter note
{duration: "8", beats: 0.5}, // eighth note
// You can add more (16th, etc.) if time allows
];
// For simplicity we will generate rhythms that are sums of these durations fitting the full bar
// Given a time signature (e.g., 4/4), generate a valid rhythm for one bar randomly
function generateRhythm(randomFunc, timeSig) {
let beatsTotal = timeSig.num * (4 / timeSig.denom);
let beatsLeft = beatsTotal;
let rhythm = [];
// Choose notes from noteDurations that fit the beats left
while (beatsLeft > 0) {
// Filter durations that fit in remaining beats
let available = noteDurations.filter(n => n.beats <= beatsLeft);
if (available.length === 0) break; // no fitting note (should not occur)
// Pick a random note duration from available
let choice = available[Math.floor(randomFunc() * available.length)];
rhythm.push(choice.duration);
beatsLeft -= choice.beats;
}
return rhythm;
}
// Generate random notes for the rhythm, within the key (simplified, choose from scale notes)
// For simplicity, just choose notes on one octave (C4 - B4)
// VexFlow note names: e.g. 'c/4', 'd#/4', 'bb/4'
// We're not accounting for accidentals based on key here, just show key name for info.
const scaleNotes = ['c', 'd', 'e', 'f', 'g', 'a', 'b'];
// We'll randomly select accidentals too, just for fun
const accidentals = ['', '#', 'b'];
function generateNote(randomFunc) {
let note = scaleNotes[Math.floor(randomFunc() * scaleNotes.length)];
let accidental = accidentals[Math.floor(randomFunc() * accidentals.length)];
// octave between 4 and 5
let octave = 4 + Math.floor(randomFunc() * 2);
return note + accidental + "/" + octave;
}
function generateBarNotes(randomFunc, rhythm) {
// For each duration create a note object for VexFlow
return rhythm.map(duration => {
return { keys: [generateNote(randomFunc)], duration };
});
}
function clearSheet() {
const sheet = document.getElementById('sheet');
sheet.innerHTML = '';
}
function createRenderer() {
const div = document.getElementById('sheet');
div.innerHTML = "";
// Create SVG renderer and attach it to the DIV element
const renderer = new Vex.Flow.Renderer(div, Vex.Flow.Renderer.Backends.SVG);
renderer.resize(800, 200);
const context = renderer.getContext();
context.setFont("Arial", 10, "").setBackgroundFillStyle("#eed");
return {renderer, context};
}
// Main render function
function renderSheet(seed, timeSignature, keySignature, numBars) {
const {num, denom} = parseTimeSig(timeSignature);
clearSheet();
const {renderer, context} = createRenderer();
const staveWidth = 150;
const staveHeight = 120;
// seeded random function
const seedInt = cyrb53(seed);
let randomFunc = mulberry32(seedInt);
// Draw multiple staves side by side for bars
for (let i = 0; i < numBars; i++) {
const stave = new Vex.Flow.Stave(i * staveWidth + 10, 40, staveWidth - 20);
if (i === 0) {
stave.addClef("treble").addTimeSignature(timeSignature).addKeySignature(keySignature);
} else {
stave.addClef("treble");
}
stave.setContext(context).draw();
// Generate rhythm and notes
const rhythm = generateRhythm(randomFunc, {num, denom});
const notesData = generateBarNotes(randomFunc, rhythm);
// Create VexFlow StaveNote objects
const notes = notesData.map(n => new Vex.Flow.StaveNote(n));
// Add accidentals if any
notes.forEach(note => {
note.keys.forEach((k, idx) => {
if (k.includes('#')) {
note.addAccidental(idx, new Vex.Flow.Accidental("#"));
} else if (k.includes('b')) {
note.addAccidental(idx, new Vex.Flow.Accidental("b"));
}
});
});
// Create a voice in 4/4 and add notes to it from above array
const voice = new Vex.Flow.Voice({
num_beats: num,
beat_value: denom,
resolution: Vex.Flow.RESOLUTION,
});
voice.addTickables(notes);
// Format and justify the notes to stave's width.
new Vex.Flow.Formatter().joinVoices([voice]).format([voice], stave.width - 40);
// Render voice
voice.draw(context, stave);
}
}
// Helper to hash string to int for seed
// Source: https://stackoverflow.com/a/52171480/3356840
function cyrb53(str, seed = 0) {
let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
for (let i = 0, ch; i < str.length; i++) {
ch = str.charCodeAt(i);
h1 = Math.imul(h1 ^ ch, 2654435761);
h2 = Math.imul(h2 ^ ch, 1597334677);
}
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
return 4294967296 * (2097151 & h2) + (h1 >>> 0);
}
// Setup event
document.getElementById('generateBtn').addEventListener('click', () => {
const seed = document.getElementById('seedInput').value.trim();
const timeSignature = document.getElementById('timeSig').value;
const keySignature = document.getElementById('keySig').value;
const numBars = parseInt(document.getElementById('numBars').value, 10);
renderSheet(seed, timeSignature, keySignature, numBars);
});
// Initial render
window.onload = () => {
document.getElementById('generateBtn').click();
}
</script>
</body>
</html>