Creating a random sheet music generator is an interesting project! Below, I'll provide a simple web app that generates random sheet music bars based on:
A seed (to reproduce the same sequence)
Time signature (e.g., 4/4, 3/4)
Rhythms (using common note durations)
Key (major scale keys)
It'll generate a sequence of random notes in the specified key and rhythm and display it visually using SVG for the staff and notes.
Features:
Input seed (random or user-provided)
Select time signature (4/4, 3/4)
Select key (C, G, D, F major)
Number of bars
Generates simple quarter/eighth/sixteenth note rhythms filling the bar
Shows bars with a treble clef & staff
Note: This is a simplified example, no accidentals or rests (only notes), and no real music engraving library used (like VexFlow). For advanced rendering, consider VexFlow or similar.
Full HTML + CSS + JS Code:
html
<!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: Arial, sans-serif;
margin: 1rem;
background: #f0f0f0;
}
label {
margin-right: 0.5rem;
}
input, select, button {
margin: 0.2rem 1rem 0.2rem 0;
padding: 0.3rem 0.5rem;
font-size: 1rem;
}
#sheet {
background: white;
border: 1px solid #ccc;
padding: 1rem;
margin-top: 1rem;
overflow-x: auto;
}
svg {
display: block;
margin: auto;
}
</style>
</head>
<body>
<h1>Random Sheet Music Generator</h1>
<form id="musicForm">
<label>Seed (leave blank for random): <input type="text" id="seed" /></label>
<label>Key:
<select id="key">
<option value="C">C Major</option>
<option value="G">G Major</option>
<option value="D">D Major</option>
<option value="F">F Major</option>
</select>
</label>
<label>Time Signature:
<select id="timeSig">
<option value="4/4">4/4</option>
<option value="3/4">3/4</option>
</select>
</label>
<label>Bars:
<input type="number" id="bars" value="4" min="1" max="16" />
</label>
<button type="submit">Generate</button>
</form>
<div id="sheet"></div>
<script>
// PRNG from seed for reproducibility (Mulberry32)
function mulberry32(a) {
return function() {
a |= 0; a = a + 0x6D2B79F5 | 0;
var t = Math.imul(a ^ a >>> 15, 1 | a);
t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
return ((t ^ t >>> 14) >>> 0) / 4294967296;
}
}
// Map key to notes (C major scale as base, G/F/D add accidentals)
const keyNotes = {
C: ['C', 'D', 'E', 'F', 'G', 'A', 'B'],
G: ['G', 'A', 'B', 'C', 'D', 'E', 'F#'],
D: ['D', 'E', 'F#', 'G', 'A', 'B', 'C#'],
F: ['F', 'G', 'A', 'Bb', 'C', 'D', 'E'],
};
// Note letter to MIDI-like pitch for positioning on staff (C4=60)
const letterToPitch = {
'C': 60,
'C#': 61,
'D': 62,
'D#': 63,
'E': 64,
'F': 65,
'F#': 66,
'G': 67,
'G#': 68,
'A': 69,
'A#': 70,
'B': 71,
'Bb': 70
};
// Note duration in quarter note units and names, with rhythmic value for drawing
const durations = [
{ name: 'quarter', value: 1 },
{ name: 'eighth', value: 0.5 },
{ name: 'sixteenth', value: 0.25 }
];
// Note SVG paths for noteheads, stems, flags (simplified)
const noteheadRadius = 7;
const staffTopY = 40;
const lineSpacing = 10;
const noteheadsPath = (cx, cy, filled = true) => {
// Ellipse notehead rotated 45 degrees
return `<ellipse cx="${cx}" cy="${cy}" rx="${noteheadRadius}" ry="${noteheadRadius * 0.6}"
fill="${filled ? 'black' : 'white'}" stroke="black" stroke-width="1" transform="rotate(-45, ${cx}, ${cy})"/>`;
};
const stemPath = (cx, cy, up = true) => {
// Vertical line stem about 30px
if (up) {
return `<line x1="${cx + noteheadRadius}" y1="${cy}" x2="${cx + noteheadRadius}" y2="${cy - 30}" stroke="black" stroke-width="1.5"/>`;
} else {
return `<line x1="${cx - noteheadRadius}" y1="${cy}" x2="${cx - noteheadRadius}" y2="${cy + 30}" stroke="black" stroke-width="1.5"/>`;
}
};
const flagPath = (cx, cy, duration, up = true) => {
// Simple curved flag for eighth and sixteenth notes only
if (duration === 'eighth') {
const d = up
? `M${cx + noteheadRadius},${cy - 30} q5,5 0,10`
: `M${cx - noteheadRadius},${cy + 30} q-5,-5 0,-10`;
return `<path d="${d}" stroke="black" stroke-width="1" fill="none"/>`;
} else if(duration === 'sixteenth') {
// Two flags
const d1 = up
? `M${cx + noteheadRadius},${cy - 30} q5,5 0,10`
: `M${cx - noteheadRadius},${cy + 30} q-5,-5 0,-10`;
const d2 = up
? `M${cx + noteheadRadius},${cy - 20} q5,5 0,10`
: `M${cx - noteheadRadius},${cy + 20} q-5,-5 0,-10`;
return `<path d="${d1}" stroke="black" stroke-width="1" fill="none"/>
<path d="${d2}" stroke="black" stroke-width="1" fill="none"/>`;
}
return '';
};
// Translate pitch to y-position on staff (middle C is on ledger line below staff)
// Staff lines: E4=64 at bottom line (space), let's define line 1 as bottom line = pitch 64 (E4)
function pitchToY(pitch) {
// Middle line: B4 = 71 at line 3 (Y = staffTopY + 2 * lineSpacing)
// Line 1 (bottom): E4 = 64
// Each step (line or space) corresponds to 1 pitch step
// Calculation:
// pitch 64 (E4) = staffTopY + 4 * lineSpacing (bottom line)
// pitch 65 (F4) = bottom line + space upwards = 4 * lineSpacing - 5
// We invert Y axis: higher pitch = smaller Y
const bottomLinePitch = 64;
return staffTopY + 4 * lineSpacing - (pitch - bottomLinePitch) * (lineSpacing / 2);
}
// Generate rhythmic pattern filling the measure exactly
function generateRhythm(rng, beatsPerBar) {
const pattern = [];
let total = 0;
while(total < beatsPerBar) {
// Pick duration that fits the remaining space
const maxDur = beatsPerBar - total;
const candidates = durations.filter(d => d.value <= maxDur);
if(!candidates.length) break;
const dur = candidates[Math.floor(rng() * candidates.length)];
pattern.push(dur);
total += dur.value;
}
return pattern;
}
// Generate random notes from key
function generateBarNotes(rng, keyNotes, rhythm) {
return rhythm.map(dur => {
// Pick a random note from the key
const note = keyNotes[Math.floor(rng() * keyNotes.length)];
// Return pitch letter + duration
return { note, duration: dur.name, value: dur.value };
});
}
function createSVGElement(tag, attrs = {}) {
const el = document.createElementNS("http://www.w3.org/2000/svg", tag);
for(let attr in attrs) {
el.setAttribute(attr, attrs[attr]);
}
return el;
}
function drawStaff(svg, x, y, width) {
// Draw 5 staff lines
for(let i=0; i<5; i++) {
const line = createSVGElement('line', {
x1: x,
y1: y + i * lineSpacing,
x2: x + width,
y2: y + i * lineSpacing,
stroke: 'black',
'stroke-width': 1,
});
svg.appendChild(line);
}
}
// Draw treble clef (simple G-clef glyph)
function drawTrebleClef(svg, x, y) {
// Use Unicode treble clef symbol as text for simplicity
const text = createSVGElement('text', { x, y: y + 4 * lineSpacing, 'font-size': '36px', 'font-family': 'Arial', fill: 'black' });
text.textContent = '𝄞';
svg.appendChild(text);
}
// Draw time signature (numerator and denominator)
function drawTimeSignature(svg, x, y, timeSig) {
const [num, den] = timeSig.split('/');
const numText = createSVGElement('text', { x, y: y + 2 * lineSpacing, 'font-size': '20px', 'font-family': 'Arial', fill: 'black' });
numText.textContent = num;
svg.appendChild(numText);
const denText = createSVGElement('text', { x, y: y + 3 * lineSpacing + 8, 'font-size': '20px', 'font-family': 'Arial', fill: 'black' });
denText.textContent = den;
svg.appendChild(denText);
}
// Draw single note
function drawNote(svg, cx, y, duration) {
// Stem direction: up if note below middle line (B4 = pitch 71 line 3)
const stemUp = y > (staffTopY + 2 * lineSpacing);
// Draw notehead
svg.insertAdjacentHTML('beforeend', noteheadsPath(cx, y));
// Add stem for notes shorter than whole (all here)
const stem = createSVGElement('line', {
x1: cx + (stemUp ? noteheadRadius : -noteheadRadius),
y1: y,
x2: cx + (stemUp ? noteheadRadius : -noteheadRadius),
y2: stemUp ? y - 30 : y + 30,
stroke: 'black',
'stroke-width': 1.5,
});
svg.appendChild(stem);
// Draw flags for eighth or sixteenth notes
if(duration === 'eighth' || duration === 'sixteenth') {
svg.insertAdjacentHTML('beforeend', flagPath(cx, y, duration, stemUp));
}
}
function generateSheet(seedInput, keyInput, timeSignature, barsCount) {
const seed = seedInput || Math.floor(Math.random()*1e9).toString();
const rng = mulberry32(hashCode(seed));
const [beatsPerBar, beatUnit] = timeSignature.split('/').map(Number);
const notesInKey = keyNotes[keyInput];
const svgWidth = barsCount * 220 + 60;
const svgHeight = 150;
const svg = createSVGElement('svg', { width: svgWidth, height: svgHeight });
// Draw global staff (all bars)
drawStaff(svg, 50, staffTopY, barsCount * 210);
drawTrebleClef(svg, 10, staffTopY);
drawTimeSignature(svg, 45, staffTopY, timeSignature);
// Draw bar lines and notes
for(let bar=0; bar<barsCount; bar++) {
const barStartX = 50 + bar * 210;
// Draw bar line at start
if(bar > 0) {
const barLine = createSVGElement('line', {
x1: barStartX, y1: staffTopY, x2: barStartX, y2: staffTopY + 4 * lineSpacing,
stroke: 'black',
'stroke-width': 1,
});
svg.appendChild(barLine);
}
// Generate rhythm pattern
const rhythm = generateRhythm(rng, beatsPerBar);
const notes = generateBarNotes(rng, notesInKey, rhythm);
// Draw notes evenly spaced in the bar width
const spacing = 210 / notes.length;
notes.forEach((noteObj, i) => {
// Determine pitch for drawing
const pitch = letterToPitch[noteObj.note];
let y = pitchToY(pitch);
// x position of note
const cx = barStartX + spacing / 2 + i * spacing;
drawNote(svg, cx, y, noteObj.duration);
});
}
// Draw end bar line at end
const endBarLine = createSVGElement('line', {
x1: 50 + barsCount * 210, y1: staffTopY, x2: 50 + barsCount * 210, y2: staffTopY + 4 * lineSpacing,
stroke: 'black',
'stroke-width': 2,
});
svg.appendChild(endBarLine);
return { svg, seed };
}
// Simple string hash function to generate seed number from string
function hashCode(str) {
let hash = 0, i, chr;
if(str.length === 0) return hash;
for(i=0; i<str.length; i++) {
chr = str.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // to 32bit int
}
return hash;
}
document.getElementById('musicForm').addEventListener('submit', e => {
e.preventDefault();
const seedInput = document.getElementById('seed').value.trim();
const keyInput = document.getElementById('key').value;
const timeSignature = document.getElementById('timeSig').value;
const barsCount = Number(document.getElementById('bars').value);
const sheetDiv = document.getElementById('sheet');
sheetDiv.innerHTML = ''; // Clear previous
const { svg, seed } = generateSheet(seedInput, keyInput, timeSignature, barsCount);
sheetDiv.appendChild(svg);
if(!seedInput) {
alert(`Generated seed: ${seed}`);
}
});
</script>
</body>
</html>
How to Use
Paste the above code into an .html file and open it in a modern browser.
Optionally enter a seed string: this determines the random sequence, so the same seed plus key/time signature/bars will always generate the same sheet.
Select a key, time signature, and number of bars.
Click Generate to see the random sheet music bars.
If no seed was entered, the app alerts the generated seed so you can reuse it and get the same music later.
Notes
This code uses a simple PRNG for reproducibility.
Notes are randomly selected from the major scale of the chosen key.
Rhythms fill bars exactly (simple quarter/eighth/sixteenth only).
Notes are drawn on a basic staff using SVG.
No rests or accidentals beyond the key signature.
For advanced notation rendering, check out libraries like VexFlow.
If you want me to enhance this to support rests, accidentals, different clefs, or export to MIDI, just ask!