Creating a random sheet music generator with bars, seed, time signature, rhythm, keys, and treble+bass staves is a fun and moderately complex project. Below, I'll provide a simple yet extendable example using HTML, CSS, and JavaScript.
This example will generate random measures with random notes according to the selected time signature and key, display the treble and bass clefs, and allow a seed to reproduce the same sequence.
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: Arial, sans-serif;
margin: 2rem;
background: #f9f9f9;
color: #333;
}
label {
margin-right: 1rem;
}
select, input[type=number], input[type=text] {
margin-right: 1rem;
padding: 5px;
font-size: 1rem;
}
#music {
margin-top: 2rem;
border: 1px solid #ccc;
background: white;
padding: 1rem;
display: inline-block;
}
button {
padding: 0.5rem 1rem;
font-size: 1rem;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Random Sheet Music Generator</h1>
<div>
<label for="seedInput">Seed:</label>
<input type="text" id="seedInput" placeholder="any string, e.g. 'abc123'" />
<label for="barsInput">Bars:</label>
<input type="number" id="barsInput" min="1" max="20" value="4" />
<label for="timeSigSelect">Time Signature:</label>
<select id="timeSigSelect">
<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 for="keySelect">Key Signature:</label>
<select id="keySelect">
<option value="C" selected>C Major / A minor</option>
<option value="G">G Major / E minor</option>
<option value="D">D Major / B minor</option>
<option value="F">F Major / D minor</option>
<option value="Bb">Bb Major / G minor</option>
<option value="Eb">Eb Major / C minor</option>
</select>
<button id="generateBtn">Generate</button>
</div>
<div id="music"></div>
<script src="https://unpkg.com/vexflow/releases/vexflow-min.js"></script>
<script>
// Initialize VexFlow
const VF = Vex.Flow;
const musicDiv = document.getElementById('music');
const seedInput = document.getElementById('seedInput');
const barsInput = document.getElementById('barsInput');
const timeSigSelect = document.getElementById('timeSigSelect');
const keySelect = document.getElementById('keySelect');
const generateBtn = document.getElementById('generateBtn');
// Simple seeded random generator (mulberry32)
// https://stackoverflow.com/a/47593316/4014959
function mulberry32(seed) {
return function() {
let t = seed += 0x6D2B79F5;
t = Math.imul(t ^ (t >>> 15), 1 | t);
t ^= t + Math.imul(t ^ (t >>> 7), 61 | t);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
}
// Convert seed string into 32-bit int
function xmur3(str) {
for(var i = 0, h = 1779033703 ^ str.length; i < str.length; i++) {
h = Math.imul(h ^ str.charCodeAt(i), 3432918353);
h = (h << 13) | (h >>> 19);
}
return function() {
h = Math.imul(h ^ (h >>> 16), 2246822507);
h = Math.imul(h ^ (h >>> 13), 3266489909);
return (h ^= h >>> 16) >>> 0;
}
}
// Utilities to get note names in key - simplified major scale notes
// We'll random notes within one octave for demo purposes
// Bass notes same - but lower octave
const scaleNotes = {
'C': ['c/4', 'd/4', 'e/4', 'f/4', 'g/4', 'a/4', 'b/4'],
'G': ['g/4', 'a/4', 'b/4', 'c/5', 'd/5', 'e/5', 'fis/5'], // F# = fis in vexflow
'D': ['d/4', 'e/4', 'fis/4', 'g/4', 'a/4', 'b/4', 'cis/5'], // C# = cis
'F': ['f/4', 'g/4', 'a/4', 'bes/4', 'c/5', 'd/5', 'e/5'], // Bb = bes
'Bb': ['bb/3', 'c/4', 'd/4', 'eb/4', 'f/4', 'g/4', 'a/4'],
'Eb': ['eb/3', 'f/3', 'g/3', 'ab/3', 'bb/3', 'c/4', 'd/4'],
};
// For bass clef - lower octave:
function convertToBass(note) {
// e.g. c/4 -> c/3, d/4->d/3, etc.
return note.replace(/\/(\d)/, (m, p1) => '/' + (parseInt(p1) - 1));
}
// Possible rhythms (simplified) with durations:
// durations according to standard: "q"=quarter, "h"=half, "8"=eighth
// Let's limit rhythms to quarter, eighth, half notes for this demo.
const rhythms = [
{duration: 'q', beats: 1},
{duration: 'h', beats: 2},
{duration: '8', beats: 0.5},
];
// Given time signature, return total beats
function getTotalBeats(timeSig) {
const parts = timeSig.split('/');
const beatsPerMeasure = parseInt(parts[0],10);
return beatsPerMeasure;
}
// Generate rhythm pattern that fits total beats
function generateRhythm(random, totalBeats) {
let beatsLeft = totalBeats;
const pattern = [];
while (beatsLeft > 0) {
// choose rhythms that fit the beats left
const available = rhythms.filter(r => r.beats <= beatsLeft);
if (available.length === 0) break; // should not happen
const choice = available[Math.floor(random()*available.length)];
pattern.push(choice.duration);
beatsLeft -= choice.beats;
}
return pattern;
}
// Generate notes for given rhythm pattern and scale
// We'll pick random scale notes for treble and bass separately
// Output is arrays of note objects for treble and bass
function generateNotes(random, rhythmPattern, scale) {
const trebleNotes = [];
const bassNotes = [];
for (const dur of rhythmPattern) {
// Random note from scale
const trebleNote = scale[Math.floor(random()*scale.length)];
const bassNote = convertToBass(trebleNote);
trebleNotes.push({ keys: [trebleNote], duration: dur });
bassNotes.push({ keys: [bassNote], duration: dur });
}
return {trebleNotes, bassNotes};
}
// Clear previous rendering
function clearMusic() {
musicDiv.innerHTML = '';
}
// Main generate function
function generateMusic() {
clearMusic();
let seedStr = seedInput.value.trim();
if (!seedStr) {
alert('Please enter a seed!');
return;
}
// Setup seeded rng
const seedFunc = xmur3(seedStr);
const seedNum = seedFunc();
const rand = mulberry32(seedNum);
const bars = parseInt(barsInput.value, 10);
if (bars < 1 || bars > 20) {
alert('Bars must be between 1 and 20');
return;
}
const timeSig = timeSigSelect.value;
const key = keySelect.value;
const totalBeats = getTotalBeats(timeSig);
// Create VF Renderer
const VF_WIDTH = 700;
const VF_HEIGHT = 200 * bars;
const div = document.createElement('div');
musicDiv.appendChild(div);
const renderer = new VF.Renderer(div, VF.Renderer.Backends.SVG);
renderer.resize(VF_WIDTH, VF_HEIGHT);
const context = renderer.getContext();
context.setFont('Arial', 10, '').setBackgroundFillStyle('#eed');
// Setup stave vertical spacing
const staveSpacing = 180;
for (let i = 0; i < bars; i++) {
// Generate rhythm
const rhythmPattern = generateRhythm(rand, totalBeats);
// Generate notes for treble and bass
const { trebleNotes, bassNotes } = generateNotes(rand, rhythmPattern, scaleNotes[key]);
// Treble Stave
const staveTreble = new VF.Stave(10, i * staveSpacing, VF_WIDTH - 20);
staveTreble.addClef('treble').addTimeSignature(timeSig).addKeySignature(key);
staveTreble.setContext(context).draw();
// Bass Stave below treble
const staveBass = new VF.Stave(10, i * staveSpacing + 90, VF_WIDTH - 20);
staveBass.addClef('bass').addKeySignature(key);
staveBass.setContext(context).draw();
// Create notes
const notesTreble = trebleNotes.map(n => new VF.StaveNote(n)
.addModifier(new VF.Articulation("a>").setPosition(4), 0)); // Just a demo articulation
const notesBass = bassNotes.map(n => new VF.StaveNote(n));
// Create voice for treble & bass
const voiceTreble = new VF.Voice({num_beats: totalBeats, beat_value: parseInt(timeSig.split('/')[1])});
voiceTreble.addTickables(notesTreble);
const voiceBass = new VF.Voice({num_beats: totalBeats, beat_value: parseInt(timeSig.split('/')[1])});
voiceBass.addTickables(notesBass);
// Format and justify the notes to the stave's width
const formatter = new VF.Formatter()
.joinVoices([voiceTreble]).format([voiceTreble], VF_WIDTH - 150);
const formatterBass = new VF.Formatter()
.joinVoices([voiceBass]).format([voiceBass], VF_WIDTH - 150);
// Render voices
voiceTreble.draw(context, staveTreble);
voiceBass.draw(context, staveBass);
}
}
generateBtn.addEventListener('click', generateMusic);
</script>
</body>
</html>
If you want, I can help extend this with more rhythmic diversity, rests, accidentals, or playback using Tone.js. Let me know!