cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

Quick-add: + add another resource

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

Quick-add: + add another resource

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

            
              <html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/@magenta/music@1.1.1"></script>
  </head>

  <body><center><div id='content'>
    <h1>Multitrack Chords</h1>
    <div id='status'>Loading model (25 MB)...</div>
    <div id='settings'>
      <div id='style1'>
        <br><br><br><br><br>
        <h2>Style 1</h2>
        <button id='sample1' disabled>Random</button><br><br>
      </div>
      <div id='style2'>
        <br><br><br><br><br>
        <h2>Style 2</h2>
        <button id='sample2' disabled>Random</button><br><br>
      </div>
      <br><br>
      <div id='position'>
        <button id='changeChords' disabled>Change Chords</button><br><br>
        <div id='chords'>
          <input id='chord1' type='text' value='Dm' disabled>
          <input id='chord2' type='text' value='F' disabled>
          <input id='chord3' type='text' value='Am' disabled>
          <input id='chord4' type='text' value='G' disabled>
        </div>
        <br><br>
        <input id='alpha' type='range' min='0' max='5' value='0' disabled>
      </div>
    </div>
    <br><br>
    <button id='play' disabled>Play</button><br><br>
    <button id='download' disabled>Save as MIDI</button><br>
  </div>
  <p id='fineprint'>Uses samples from <a href='https://www.polyphone-soundfonts.com/en/files/27-instrument-sets/256-sgm-v2-01'>SGM</a> with modifications by <a href="https://sites.google.com/site/soundfonts4u/">John Nebauer</a>.  May work poorly on mobile.
  </center></body>
</html>
            
          
!
            
              @import url(https://fonts.googleapis.com/css?family=Roboto);

body {text-align:center; font-family:Roboto; font-size:12px; margin-top:20px; background-color:white}
h1 {font-size:24px}
h2 {font-size:16px}
input {text-align:center; font-size:14px; width:300px}
#status {color:black}
#content {width:500px; padding:10px 20px; background-color:lightgray; border:1px solid black; border-radius:20px}
#style1 {float:left}
#style2 {float:right}
#position {float:center}
#chords input {width:50px; color:gray}
button {font-size:14px; 
border:1px solid #ccc; padding:6px; display:inline-block; border-radius:5px; background-color:white; color:black}
button:disabled {color:gray}
button:focus {outline:0}
#fineprint {font-size:12px; width:500px}
            
          
!
            
              const QPM = 120;
const STEPS_PER_QUARTER = 24;
const Z_DIM = 256;
const HUMANIZE_SECONDS = 0.01;
const MAX_PAN = 0.2;

const MIN_DRUM = 35;
const MAX_DRUM = 81;

const tf = mm.tf;

// Set up Multitrack MusicVAE.
const model = new mm.MusicVAE('https://storage.googleapis.com/magentadata/js/checkpoints/music_vae/multitrack_chords');

// Set up effects chain.
const globalCompressor = new mm.Player.tone.MultibandCompressor();
const globalReverb = new mm.Player.tone.Freeverb(0.25);
const globalLimiter = new mm.Player.tone.Limiter();

globalCompressor.connect(globalReverb);
globalReverb.connect(globalLimiter);
globalLimiter.connect(mm.Player.tone.Master);

// Set up per-program effects.
const programMap = new Map();
for (let i=0; i<128; i++) {
  const programCompressor = new mm.Player.tone.Compressor();
  const pan = 2 * MAX_PAN * Math.random() - MAX_PAN;
  const programPanner = new mm.Player.tone.Panner(pan);  
  programMap.set(i, programCompressor);
  programCompressor.connect(programPanner);
  programPanner.connect(globalCompressor);
}

// Set up per-drum effects.
const drumMap = new Map();
for (let i=MIN_DRUM; i<=MAX_DRUM; i++) {
  const drumCompressor = new mm.Player.tone.Compressor();
  const pan = 2 * MAX_PAN * Math.random() - MAX_PAN;
  const drumPanner = new mm.Player.tone.Panner(pan);
  drumMap.set(i, drumCompressor);
  drumCompressor.connect(drumPanner);  
  drumPanner.connect(globalCompressor);
}

// Set up SoundFont player.
const player = new mm.SoundFontPlayer('https://storage.googleapis.com/download.magenta.tensorflow.org/soundfonts_js/sgm_plus', globalCompressor, programMap, drumMap);

// Get UI elements.
const status = document.getElementById('status');
const changeChordsButton = document.getElementById('changeChords');
const playButton = document.getElementById('play');
const sampleButton1 = document.getElementById('sample1');
const sampleButton2 = document.getElementById('sample2');
const alphaSlider = document.getElementById('alpha');
const saveButton = document.getElementById('download');

const chordInputs = [
  document.getElementById('chord1'),
  document.getElementById('chord2'),
  document.getElementById('chord3'),
  document.getElementById('chord4')
];

const numSteps = +alphaSlider.max + 1;
const numChords = chordInputs.length;

// Declare style / sequence variables.
var z1, z2;
var chordSeqs;
var progSeqs;

var changingChords = false;
var playing = false;

var chords = chordInputs.map(c => c.value);

// Sample a latent vector.
function generateSample(doneCallback) {
  const z = tf.randomNormal([1, Z_DIM]);
  z.data().then(zArray => {
    z.dispose();
    doneCallback(zArray);
  });
}

// Randomly adjust note times.
function humanize(s) {
  const seq = mm.sequences.clone(s);
  seq.notes.forEach((note) => {
    const offset = HUMANIZE_SECONDS * (Math.random() - 0.5);
    if (seq.notes.startTime + offset < 0) {
      offset = -seq.notes.startTime;
    }
    if (seq.notes.endTime > seq.totalTime) {
      offset = seq.totalTime - seq.notes.endTime;
    }
    seq.notes.startTime += offset;
    seq.notes.endTime += offset;
  });
  return seq;
}

// Construct spherical linear interpolation tensor.
function slerp(z1, z2, n) {
  const norm1 = tf.norm(z1);
  const norm2 = tf.norm(z2);
  const omega = tf.acos(tf.matMul(tf.div(z1, norm1),
                                  tf.div(z2, norm2),
                                  false, true));
  const sinOmega = tf.sin(omega);
  const t1 = tf.linspace(1, 0, n);
  const t2 = tf.linspace(0, 1, n);
  const alpha1 = tf.div(tf.sin(tf.mul(t1, omega)), sinOmega).as2D(n, 1);
  const alpha2 = tf.div(tf.sin(tf.mul(t2, omega)), sinOmega).as2D(n, 1);
  const z = tf.add(tf.mul(alpha1, z1), tf.mul(alpha2, z2));
  return z;
}

// Concatenate multiple NoteSequence objects.
function concatenateSequences(seqs) {
  const seq = mm.sequences.clone(seqs[0]);
  let numSteps = seqs[0].totalQuantizedSteps;
  for (let i=1; i<seqs.length; i++) {
    const s = mm.sequences.clone(seqs[i]);
    s.notes.forEach(note => {
      note.quantizedStartStep += numSteps;
      note.quantizedEndStep += numSteps;
      seq.notes.push(note);
    });
    numSteps += s.totalQuantizedSteps;
  }
  seq.totalQuantizedSteps = numSteps;
  return seq;
}

// Interpolate the two styles for a single chord.
function interpolateSamples(chord, doneCallback) {
  const z1Tensor = tf.tensor2d(z1, [1, Z_DIM]);
  const z2Tensor = tf.tensor2d(z2, [1, Z_DIM]);
  const zInterp = slerp(z1Tensor, z2Tensor, numSteps);
  
  model.decode(zInterp, undefined, [chord], STEPS_PER_QUARTER)
    .then(sequences => doneCallback(sequences));
}

// Generate interpolations for all chords.
function generateInterpolations(chordIndex, result, doneCallback) {
  if (chordIndex === numChords) {
    doneCallback(result);
  } else {
    interpolateSamples(chords[chordIndex], seqs => {
      for (let i=0; i<numSteps; i++) {
        result[i].push(seqs[i]);
      }
      generateInterpolations(chordIndex + 1, result, doneCallback);
    })
  }
}

// Generate chord progression for each alpha.
function generateProgressions(doneCallback) {
  let temp = [];
  for (let i=0; i<numSteps; i++) {
    temp.push([]);
  }
  generateInterpolations(0, temp, seqs => {
    chordSeqs = seqs;
    concatSeqs = chordSeqs.map(s => concatenateSequences(s));
    progSeqs = concatSeqs.map(seq => {
      const mergedSeq = mm.sequences.mergeInstruments(seq);
      const progSeq = mm.sequences.unquantizeSequence(mergedSeq);
      progSeq.ticksPerQuarter = STEPS_PER_QUARTER;
      return progSeq;
    });
    
    const fullSeq = concatenateSequences(concatSeqs);
    const mergedFullSeq = mm.sequences.mergeInstruments(fullSeq);

    setLoadingState();
    player.loadSamples(mergedFullSeq)
      .then(doneCallback);
  });  
}

// Set UI state to updating styles.
function setUpdatingState() {
  status.innerText = 'Updating arrangements...';
  status.style.color = 'black';
  playButton.disabled = true;
  alphaSlider.disabled = true;
  sampleButton1.disabled = true;
  sampleButton2.disabled = true;
  saveButton.disabled = true;
  changeChordsButton.disabled = true;
  chordInputs.forEach(c => c.disabled = true);
  chordInputs.forEach(c => c.style.color = 'gray');
}

// Set UI state to updating instruments.
function setLoadingState() {
  status.innerText = 'Loading samples...';
  status.style.color = 'black';
  playButton.disabled = true;
  alphaSlider.disabled = true;
  sampleButton1.disabled = true;
  sampleButton2.disabled = true;
  saveButton.disabled = true;
  changeChordsButton.disabled = true;
  chordInputs.forEach(c => c.disabled = true);
  chordInputs.forEach(c => c.style.color = 'gray');
}

// Set UI state to playing.
function setStoppedState() {
  status.innerText = 'Ready to play!';
  status.style.color = 'black';
  playButton.innerText = 'Play';
  playButton.disabled = false;
  alphaSlider.disabled = false;
  sampleButton1.disabled = false;
  sampleButton2.disabled = false;
  saveButton.disabled = false;
  changeChordsButton.innerText = 'Change Chords';
  changeChordsButton.disabled = false;
  chordInputs.forEach(c => c.disabled = true);
  chordInputs.forEach(c => c.style.color = 'gray');
}

// Set UI state to playing.
function setPlayingState() {
  status.innerText = 'Move the slider to interpolate styles.';
  status.style.color = 'black';
  playButton.innerText = 'Stop';
  playButton.disabled = false;
  alphaSlider.disabled = false;
  sampleButton1.disabled = false;
  sampleButton2.disabled = false;
  saveButton.disabled = false;
  changeChordsButton.disabled = false;
  chordInputs.forEach(c => c.disabled = true);
  chordInputs.forEach(c => c.style.color = 'gray');
}

// Set UI state to changing chords.
function setChordChangeState() {
  status.innerText = 'Change chords (triads only) then press Done.';
  status.style.color = 'black';
  playButton.disabled = true;
  alphaSlider.disabled = true;
  sampleButton1.disabled = true;
  sampleButton2.disabled = true;
  saveButton.disabled = true;
  changeChordsButton.innerText = 'Done';
  changeChordsButton.disabled = false;
  chordInputs.forEach(c => c.disabled = false);
  chordInputs.forEach(c => c.style.color = 'black');
}

// Play the interpolated sequence for the current slider position.
function playProgression(chordIdx) {
  chordInputs.forEach(c => c.style.color = 'gray');
  chordInputs[chordIdx].style.color = 'dimgray';
  
  const idx = alphaSlider.value;
  const unquantizedSeq = mm.sequences.unquantizeSequence(chordSeqs[idx][chordIdx]);
  player.start(humanize(unquantizedSeq))
    .then(() => {
      const nextChordIdx = (chordIdx + 1) % numChords;
      playProgression(nextChordIdx);
    });
}

// Update the start style.
function updateSample1() {
  playing = false;
  setUpdatingState();
  player.stop();
  setTimeout(() => {
    generateSample(z => {
      z1 = z;
      generateProgressions(setStoppedState);
    });
  }, 0);
}

// Update the end style.
function updateSample2() {
  playing = false;
  setUpdatingState();
  player.stop();
  setTimeout(() => {
    generateSample(z => {
      z2 = z;
      generateProgressions(setStoppedState);
    });
  }, 0);
}

// Save sequence as MIDI.
function saveSequence() {
  const idx = alphaSlider.value;
  const midi = mm.sequenceProtoToMidi(progSeqs[idx]);
  const file = new Blob([midi], {type: 'audio/midi'});
    
  if (window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(file, 'prog.mid');
  } else { // Others
    const a = document.createElement('a');
    const url = URL.createObjectURL(file);
    a.href = url;
    a.download = 'prog.mid';
    document.body.appendChild(a);
    a.click();
    setTimeout(() => {
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);  
    }, 0); 
  }
}

// Start or stop playing the sequence at the current slider position.
function togglePlaying() {
  mm.Player.tone.context.resume();
  
  if (playing) {
    playing = false;
    setStoppedState();
    player.stop();
  } else {
    playing = true;
    setPlayingState();
    playProgression(0);
  }
}

// Start or finish changing chords.
function toggleChangeChords() {
  if (changingChords) {
    changingChords = false;
    chords = chordInputs.map(c => c.value);
    setUpdatingState();
    setTimeout(() => generateProgressions(setStoppedState), 0);
  } else {
    playing = false;
    changingChords = true;
    setChordChangeState();
    player.stop();
  }
}

// One of the chords has been edited.
function chordChanged() {
  const isGood = (chord) => {
    if (!chord) {
      return false;
    }
    try {
      mm.chords.ChordSymbols.pitches(chord);
      return true;
    } catch(e) {
      return false;
    }
  }
  
  var allGood = true;
  chordInputs.forEach(c => {
    if (isGood(c.value)) {
      c.style.color = 'black';
    } else {
      c.style.color = 'red';
      allGood = false;
    }
  });

  changeChordsButton.disabled = !allGood;
}

sampleButton1.onclick = updateSample1;
sampleButton2.onclick = updateSample2;
playButton.onclick = togglePlaying;
saveButton.onclick = saveSequence;
changeChordsButton.onclick = toggleChangeChords;
chordInputs.forEach(c => c.oninput = chordChanged);

model.initialize()
  .then(() => {
    setUpdatingState();
    setTimeout(() => {
      generateSample(z => {
        z1 = z;
        generateSample(z => {
          z2 = z;
          generateProgressions(setStoppedState);
        });
      });
    }, 0);
  });

            
          
!
999px
Loading ..................

Console