Creating a random sheet music generator that produces bars with a given time signature, rhythm patterns, and keys is a fun challenge! Below is a simple implementation in HTML, CSS, and JavaScript that:
- Lets you input a seed to get reproducible randomness
- Choose a time signature (e.g., 4/4, 3/4)
- Generate a random sequence of notes/rests according to the time signature
- Display the generated rhythm in a simple staff-like visualization
- Choose from common major keys to influence note pitches (optional extension)
This example focuses mostly on rhythm and notes placement, using Unicode musical symbols and basic CSS for simplicity. For full sheet music rendering, libraries like VexFlow or ABCjs would be ideal, but I’ll keep it minimal and self-contained.
Features:
- Seeded random number generator for reproducible patterns
- Time signature input (numerator/denominator)
- Key selection from C Major, G Major, D Major, etc
- Bars generation with proper rhythmic values adding up to the measure
- Visual display of notes/rests with note names on staff lines
Code example:
<!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;
padding: 1rem;
max-width: 700px;
margin: auto;
background: #fafafa;
}
h1 {
text-align: center;
}
label {
display: inline-block;
margin-top: 0.5rem;
}
input, select, button {
font-size: 1rem;
margin: 0.3rem 0.5rem 0.3rem 0;
}
.staff {
margin: 1rem 0;
position: relative;
border: 1px solid #ccc;
background: white;
padding: 1rem;
height: 120px;
}
/* Simple staff lines */
.staff-line {
position: absolute;
left: 0;
right: 0;
border-bottom: 1px solid black;
}
.staff-line1 { top: 20px; }
.staff-line2 { top: 40px; }
.staff-line3 { top: 60px; }
.staff-line4 { top: 80px; }
.staff-line5 { top: 100px; }
.bar {
display: inline-block;
vertical-align: top;
width: 140px;
border-left: 2px solid black;
height: 100px;
position: relative;
margin-right: 10px;
}
.bar:last-child {
border-right: 2px solid black;
}
.note {
position: absolute;
left: 0;
width: 20px;
font-weight: bold;
font-size: 24px;
user-select: none;
}
/* vertical positioning for notes on lines/spaces */
.pos-C4 { top: 80px; } /* middle C */
.pos-D4 { top: 70px; }
.pos-E4 { top: 60px; }
.pos-F4 { top: 50px; }
.pos-G4 { top: 40px; }
.pos-A4 { top: 30px; }
.pos-B4 { top: 20px; }
.pos-C5 { top: 10px; }
/* Accidentals */
.accidental {
font-size: 16px;
position: absolute;
left: -14px;
top: 15px;
}
/* Note names below each note */
.note-label {
font-size: 10px;
position: absolute;
top: 100px;
width: 20px;
text-align: center;
}
</style>
</head>
<body>
<h1>Random Sheet Music Generator</h1>
<label>Seed:
<input type="text" id="seed" value="1234" />
</label>
<label>Bars:
<input type="number" id="bars" min="1" max="8" value="4" />
</label><br/>
<label>Time Signature:
<input type="number" id="ts-top" min="1" max="12" value="4" style="width: 40px"/>
/
<select id="ts-bottom">
<option value="4" selected>4 (quarter)</option>
<option value="8">8 (eighth)</option>
<option value="2">2 (half)</option>
</select>
</label>
<label>Key:
<select id="key-select">
<option value="C">C Major</option>
<option value="G">G Major</option>
<option value="D">D Major</option>
<option value="A">A Major</option>
<option value="E">E Major</option>
<option value="F">F Major</option>
<option value="Bb">Bb Major</option>
</select>
</label>
<button id="generate">Generate</button>
<div id="output"></div>
<script>
// Simple seeded PRNG (Mulberry32)
function mulberry32(a) {
return function() {
var t = a += 0x6D2B79F5;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
// Notes in C major scale (simplified) starting from middle C
// We'll allow pitches: C4(60), D4(62), E4(64), F4(65), G4(67), A4(69), B4(71), C5(72)
// We'll map pitch numbers to positions and accidentals
const notePositions = {
60: 'pos-C4',
62: 'pos-D4',
64: 'pos-E4',
65: 'pos-F4',
67: 'pos-G4',
69: 'pos-A4',
71: 'pos-B4',
72: 'pos-C5',
};
// Map keys to sharps/flats
const keySignatures = {
'C': {},
'G': { 'F': '#' },
'D': { 'F': '#', 'C': '#' },
'A': { 'F': '#', 'C': '#', 'G': '#' },
'E': { 'F': '#', 'C': '#', 'G': '#', 'D': '#' },
'F': { 'B': 'b' },
'Bb': { 'B': 'b', 'E':'b' }
};
// Rhythm note durations relative to whole note (1.0)
const durations = [
{ name: 'whole', value: 1.0, symbol: '𝅝', lengthName: 'whole' },
{ name: 'half', value: 0.5, symbol: '𝅗𝅥', lengthName: 'half' },
{ name: 'quarter', value: 0.25, symbol: '♩', lengthName: 'quarter' },
{ name: 'eighth', value: 0.125, symbol: '♪', lengthName: 'eighth' },
{ name: 'sixteenth', value: 0.0625, symbol: '♬', lengthName: 'sixteenth' },
];
// For simplicity, we'll generate notes and rests randomly to fill a bar
const rhythmValues = [
0.25, // quarter
0.125, // eighth
0.5, // half
0.0625, // 16th
];
const rhythmSymbols = {
0.5: '𝅗𝅥', // half note
0.25: '♩', // quarter note
0.125: '♪', // eighth note
0.0625: '♬', // sixteenth note
};
const restSymbols = {
1.0: '𝄻',
0.5: '𝄼',
0.25: '𝄽',
0.125: '𝄾',
0.0625: '𝄿',
};
// Convert note MIDI number to name + accidental based on Key
function midiToNoteName(midiNum, keySig) {
// MidiNum to letter in C major
// 60 = C4, 61 C#4/Db4, etc.
const noteNames = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#','G','G#','A','A#','B'];
let octave = Math.floor(midiNum / 12) - 1;
let noteIndex = midiNum % 12;
let letter = noteNames[noteIndex].replace('#', '');
// Determine if the note is sharp and should be flatted/sharped with key signature
let accidental = '';
if(noteNames[noteIndex].includes('#')) {
// Check key signature
let naturalLetter = letter;
if(keySig[naturalLetter]) {
if(keySig[naturalLetter] === '#'){
accidental = ''; // sharp allowed by key
} else if(keySig[naturalLetter] === 'b') {
// Using flat instead of sharp
accidental = '♭';
letter = String.fromCharCode(letter.charCodeAt(0) + 1); // Next natural note letter, for display simplification we keep it simple
}
} else {
accidental = '♯';
}
}
return { name: letter + octave, accidental: accidental};
}
// Generate notes for a bar using seed RNG
function generateBarNotes(rng, beats, beatUnit, keySig) {
// beats = numerator (e.g., 4)
// beatUnit = denominator (e.g., 4)
// Time signature fraction is beats * (1/beatUnit) whole notes
const barLengthWholeNotes = beats * (1 / beatUnit);
let sum = 0;
const notes = [];
while(sum < barLengthWholeNotes - 0.00001) {
// Possible rhythms that fit the remaining space
let maxDur = barLengthWholeNotes - sum;
// Filter durations that fit
let validDurations = rhythmValues.filter(d => d <= maxDur);
// Pick random duration
let dur = validDurations[Math.floor(rng() * validDurations.length)];
// 20% chance to be a rest
let isRest = rng() < 0.2;
let pitch = null;
if(!isRest) {
// Pick random pitch in C4-C5 scale (60-72)
// Also apply key signature accidentals later
let scalePitches = [60,62,64,65,67,69,71,72];
pitch = scalePitches[Math.floor(rng() * scalePitches.length)];
}
notes.push({ duration: dur, isRest: isRest, pitch: pitch });
sum += dur;
}
return notes;
}
function buildStaffLine(barElem, notes, keySig) {
// Clear bar contents
barElem.innerHTML = '';
// Place lines
for(let i=1; i<=5; i++) {
let line = document.createElement('div');
line.classList.add('staff-line', `staff-line${i}`);
barElem.appendChild(line);
}
// For horizontal positioning inside bar - distribute evenly:
const barWidth = barElem.clientWidth;
const noteCount = notes.length;
const noteSpacing = (barWidth - 20) / noteCount;
notes.forEach((note, i) => {
let noteDiv = document.createElement('div');
noteDiv.classList.add('note');
// Horizontal position
noteDiv.style.left = `${10 + i * noteSpacing}px`;
// Pitch name and position (if note)
if(!note.isRest) {
// Determine note position class
let posClass = notePositions[note.pitch] || 'pos-C4';
noteDiv.classList.add(posClass);
noteDiv.textContent = '♩'; // quarter note symbol
// Handle accidentals
// Determine accidental with keySig
// Simplify - only show accidental if needed
let midiNote = note.pitch;
let info = midiToNoteName(midiNote, keySig);
if(info.accidental) {
let accDiv = document.createElement('div');
accDiv.classList.add('accidental');
accDiv.textContent = info.accidental;
noteDiv.appendChild(accDiv);
}
// Note label under the note
let label = document.createElement('div');
label.classList.add('note-label');
label.style.left = '0';
label.style.top = '70px';
label.textContent = info.name;
noteDiv.appendChild(label);
} else {
// Rest
noteDiv.style.top = '50px';
noteDiv.textContent = restSymbols[note.duration] || '𝄼';
}
barElem.appendChild(noteDiv);
});
}
document.getElementById('generate').addEventListener('click', () => {
const seedInput = document.getElementById('seed').value.trim();
let seed = 0;
for(let i=0; i<seedInput.length; i++) {
seed += seedInput.charCodeAt(i);
}
const rng = mulberry32(seed);
const barsNum = parseInt(document.getElementById('bars').value) || 4;
const tsTop = parseInt(document.getElementById('ts-top').value) || 4;
const tsBottom = parseInt(document.getElementById('ts-bottom').value) || 4;
const keyName = document.getElementById('key-select').value;
const keySig = keySignatures[keyName] || {};
const outputDiv = document.getElementById('output');
outputDiv.innerHTML = '';
for(let i=0; i<barsNum; i++) {
const barDiv = document.createElement('div');
barDiv.classList.add('bar');
let notes = generateBarNotes(rng, tsTop, tsBottom, keySig);
buildStaffLine(barDiv, notes, keySig);
outputDiv.appendChild(barDiv);
}
});
</script>
</body>
</html>
How it works:
- Enter a seed string — the same seed always generates the same rhythm and notes.
- Select the number of bars and time signature (numerator/denominator).
- Pick a key (for accidentals).
- Click Generate.
- It creates a simple 5-line staff for each bar, places random notes/rests whose durations add up to the bar length.
- Notes are placed vertically to approximate pitch position (just for fun), and rests are shown with Unicode symbols.
- Accidentals appear when needed, respecting the key signature.
- Note names appear below each note.
Notes:
- This is a basic example. For real music notation, use libraries like VexFlow.
- Only handles simple rhythms and pitches in one octave.
- Time signatures other than 4/4 are easily handled by changing numerator and denominator.
- Rest durations are chosen from the note duration set.
- Visual is simplified: Unicode note/rest symbols + CSS positioning.
If you want, I can help you extend it with:
- More keys/scales
- Support for dotted notes and triplets
- Better note rendering with SVG or Canvas or VexFlow
- Playback sound with Web Audio API
Just ask!