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.

            
              <div id="visualizations">
  <div class="margin"></div>
  <div class="vis">
  <button id="mute-0" class="mute-button"></button>
  <button id="unmute-0" class="unmute-button" style="display: none"></button>     
  <button id="regen-0">&#8635;</button>
  <div id="vis-0" class="notes"></div>
  </div>
  <div class="space"></div>
  <div class="vis">
    <button id="mute-1" class="mute-button"></button>
    <button id="unmute-1" class="unmute-button" style="display: none"></button> 
    <button id="regen-1">&#8635;</button>
    <div id="vis-1" class="notes"></div>
  </div>
  <div class="space"></div>
  <div class="vis">
    <button id="mute-2" class="mute-button"></button>
    <button id="unmute-2" class="unmute-button" style="display: none"></button> 
    <button id="regen-2">&#8635;</button>
    <div id="vis-2" class="notes"></div>
  </div>
  <div class="margin"></div>
</div>
            
          
!
            
              html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  background-color: #BBDEFB;
}

#visualizations {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}


button {
  border-radius: 50%;
  width: 100px;
  height: 100px;
  margin: 0;
  border: 0;
  font-size: 40px;
  outline: none;
  cursor: pointer;
  background-color: #BBDEFB;
}
button:hover {
  background-color: #E3F2FD;
}
.mute-button, .unmute-button {
  background-size: contain;
  background-repeat: no-repeat;
  background-position: 50% 50%;
}
.mute-button {
  background-image: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/969699/mute.svg');
}
.unmute-button {
  background-image: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/969699/unmute.svg');
}
button:last-of-type {
  margin-right: 50px;
}

#visualizations {
  display: flex;
  flex-direction: column;
}
.vis {
  flex: 2;
  padding: 0 100px;
  display: flex;
  align-items: stretch;
  flex-direction: row;
}
.margin {
  flex: 2;
}
.space {
  flex: 0.5;
}
.vis button {
  align-self: center;
}
.notes {
  display: flex;
  align-items: stretch;
}
.note {
  position: relative;
}
.note .main {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
}
.note .symbol {
  flex: 1;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: 0% 50%;
}
.note .progress {
  position: absolute;
  left: 0;
  bottom: 0;
  height: 3px;
  width: 0;
  background-color: #EC407A;
}
.note.d-4n {
  width: 120px;
}
.note.d-8n {
  width: 60px;
}
.note.d-4n .symbol {
  background-image: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/969699/4n.svg');
}
.note.d-8n .symbol {
  background-image: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/969699/8n.svg');
}
.note.r.d-4n .symbol {
  background-image: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/969699/4r.svg'); 
}
.note.r.d-8n .symbol {
  background-image: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/969699/8r.svg');
}
.note.l .symbol {
  height: 80px;
}
.note.m .symbol {
  height: 100px;
}
.note.h .symbol {
  height: 120px;
}
.note.r .symbol {
  height: 60px;
}
            
          
!
            
              const c3 = new Tone.Buffer('https://s3-us-west-2.amazonaws.com/s.cdpn.io/969699/xylo-c3.mp3');
const g3 = new Tone.Buffer('https://s3-us-west-2.amazonaws.com/s.cdpn.io/969699/xylo-g3.mp3');
const c4 = new Tone.Buffer('https://s3-us-west-2.amazonaws.com/s.cdpn.io/969699/street-bell-c4.mp3');
const sounds = {
  c3: {
    h: { buffer: c3, duration: 1, offset: 0 },
    l: { buffer: c3, duration: 1, offset: 1 },
    m: { buffer: c3, duration: 1, offset: 2 }
  },
  g3: {
    h: { buffer: g3, duration: 1, offset: 0 },
    l: { buffer: g3, duration: 1, offset: 1 },
    m: { buffer: g3, duration: 1, offset: 2 }
  },
  c4: {
    h: { buffer: c4, duration: 1, offset: 0 },
    l: { buffer: c4, duration: 1, offset: 1 },
    m: { buffer: c4, duration: 1, offset: 2 }
  }
};

const grammar = tracery.createGrammar({
  pattern: ['#cell# #pattern#', '#cell#'],
  cell: ['#two#', '#three#'],
  two: ['#eighth# #eighth#', '#quarter#'],
  three: [
    '#eighth# #eighth# #eighth#',
    '#quarter# #eighth#',
    '#eighth# #quarter#'
  ],
  quarter: ['h-4n', 'l-4n', 'm-4n', 'r-4n'],
  eighth: ['h-8n', 'l-8n', 'm-8n', 'r-8n']
});

const loops = [
  {
    pan: -0.25,
    pitch: 'c4',
    gain: 0.7,
    pattern: generatePattern(grammar),
    vis: initVis(0)
  },
  {
    pan: 0,
    pitch: 'g3',
    gain: 0.6,
    pattern: generatePattern(grammar),
    vis: initVis(1)
  },
  {
    pan: 0.25,
    pitch: 'c3',
    gain: 0.9,
    pattern: generatePattern(grammar),
    vis: initVis(2)
  }
];

function generatePattern(grammar) {
  const pattern = grammar.expand('#pattern#');

  const notes = [];
  let totalDuration = '0';
  pattern.children.forEach(function visit(node) {
    if (node.children) {
      node.children.forEach(visit);
    } else if (node.raw.trim().length) {
      const [velocity, duration] = node.raw.split('-');
      notes.push({ velocity, duration, node });
      totalDuration += '+' + duration;
    }
  });
  return { pattern, notes, totalDuration };
}

Tone.Buffer.on('load', () => {
  const masterGain = new Tone.Gain(0).toMaster();
  const compressor = new Tone.Compressor().connect(masterGain);
  const delay = new Tone.Delay(0.2).connect(compressor);
  masterGain.gain.setValueAtTime(0, Tone.now());
  masterGain.gain.linearRampToValueAtTime(1, Tone.now() + 1.5);

  loops.forEach(({ pattern, pitch, pan, gain, vis }, loopIndex) => {
    const muteGain = new Tone.Gain(1).connect(delay);
    const panner = new Tone.Panner(pan).connect(muteGain);
    const player = new Tone.MultiPlayer().connect(panner);

    renderPattern(pattern, vis, loopIndex);

    const regenButton = document.querySelector(`#regen-${loopIndex}`);
    const muteButton = document.querySelector(`#mute-${loopIndex}`);
    const unmuteButton = document.querySelector(`#unmute-${loopIndex}`);

    regenButton.addEventListener('click', () => {
      pattern = generatePattern(grammar);
      renderPattern(pattern, vis, loopIndex);
    });
    unmuteButton.style.display = 'none';
    muteButton.addEventListener('click', () => {
      muteGain.gain.setValueAtTime(1, Tone.now());
      muteGain.gain.linearRampToValueAtTime(0, Tone.now() + 0.3);
      muteButton.style.display = 'none';
      unmuteButton.style.display = 'block';
      vis.container.style.opacity = 0.3;
    });
    unmuteButton.addEventListener('click', () => {
      muteGain.gain.setValueAtTime(0, Tone.now());
      muteGain.gain.linearRampToValueAtTime(1, Tone.now() + 0.3);
      muteButton.style.display = 'block';
      unmuteButton.style.display = 'none';
      vis.container.style.opacity = 1;
    });

    function playPattern(baseTime = Tone.now()) {
      // Play each note in pattern once
      let time = baseTime;
      pattern.notes.forEach((note, soundIdx) => {
        const humanize = Math.random() * 0.02 - 0.01;
        if (sounds[pitch].hasOwnProperty(note.velocity)) {
          const { buffer, offset, duration: sampleDur } = sounds[pitch][
            note.velocity
          ];
          player.start(buffer, time + humanize, offset, sampleDur, 0, gain);
        }
        Tone.Draw.schedule(() => renderPlay(note, vis), time + humanize);
        time += '+' + note.duration;
      }, baseTime);
      // Schedule next iteration
      Tone.Transport.schedule(playPattern, '+' + pattern.totalDuration);
    }
    Tone.Transport.schedule(playPattern);
  });

  Tone.Transport.bpm.value = 120;
  Tone.Transport.start();
});

function initVis(loopIndex) {
  return {
    container: document.querySelector(`#vis-${loopIndex}`),
    noteElements: new Map()
  };
}
function renderPattern(pattern, { container, noteElements }, loopIndex) {
  const fadeDelay = 250;
  const removals = [];
  for (const [note, el] of noteElements) {
    removals.push(
      new Promise(res => {
        el.animate([{ opacity: 1 }, { opacity: 0 }], {
          duration: fadeDelay,
          fill: 'forwards'
        }).onfinish = () => {
          el.remove();
          res();
        };
      })
    );
    noteElements.delete(note);
  }
  const addedEls = pattern.notes.map(note => {
    const noteEl = document.createElement('div');
    noteEl.classList.add('note');
    noteEl.classList.add(note.velocity);
    noteEl.classList.add(`d-${note.duration}`);
    const mainEl = document.createElement('div');
    mainEl.classList.add('main');
    const symbolEl = document.createElement('div');
    symbolEl.classList.add('symbol');
    mainEl.appendChild(symbolEl);
    noteEl.appendChild(mainEl);
    const progressEl = document.createElement('div');
    progressEl.classList.add('progress');
    noteEl.appendChild(progressEl);
    container.appendChild(noteEl);
    noteElements.set(note, noteEl);
    noteEl.style.opacity = 0;
    return noteEl;
  });
  Promise.all(removals).then(() => {
    addedEls.forEach(el =>
      el.animate([{ opacity: 0 }, { opacity: 1 }], {
        delay: fadeDelay,
        duration: fadeDelay,
        fill: 'forwards'
      })
    );
  });
}
function renderPlay(noteToPlay, { noteElements }) {
  let playedSeen = false;
  let lastPlayed = true;
  for (const [note, el] of noteElements) {
    if (noteToPlay === note) {
      playedSeen = true;
      bounce(el.querySelector('.symbol'));
      el
        .querySelector('.progress')
        .animate([{ width: 0, opacity: 0 }, { width: '100%', opacity: 1 }], {
          duration: 300,
          fill: 'forwards'
        });
      lastPlayed = true;
    } else {
      lastPlayed = false;
    }
  }
  if (lastPlayed) {
    for (const [note, el] of noteElements) {
      el.querySelector('.progress').animate([{ opacity: 1 }, { opacity: 0 }], {
        delay: 200,
        duration: 100,
        fill: 'forwards'
      });
    }
  }
}

function bounce(el) {
  dynamics.animate(
    el,
    { translateY: 15 },
    {
      type: dynamics.spring,
      duration: 1,
      friction: 200,
      frequency: 300,
      complete: () =>
        dynamics.animate(
          el,
          { translateY: 0 },
          {
            type: dynamics.spring,
            duration: 1000,
            friction: 200,
            anticipationSize: -20,
            anticipationStrength: 310,
            frequency: 300
          }
        )
    }
  );
}

StartAudioContext(Tone.context, document.documentElement);

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

Console