let audioContext;
let gainNode;

function startAudio() {
  audioContext = new (window.AudioContext || window.webkitAudioContext)();
  gainNode = audioContext.createGain();
  gainNode.gain.value = 0;
  gainNode.connect(audioContext.destination);
}

function muter() {
  fadeOutVolume();
}

function unMute() {
  startAudio();
  fadeInVolume();
}

function fadeInVolume() {
  gainNode.gain.setValueAtTime(0, audioContext.currentTime); // Start at 0
  gainNode.gain.linearRampToValueAtTime(1, audioContext.currentTime + 2); // Fade to full volume
}

function fadeOutVolume() {
  gainNode.gain.setValueAtTime(1, audioContext.currentTime); // Start at 1
  gainNode.gain.linearRampToValueAtTime(0, audioContext.currentTime + 2); // Fade to 0
}

export function playSound(instrument) {
  if (interacted) {
    //      const source = audioContext.createBufferSource();
    const samples = instrument.samples;
    const sampleKeys = Object.keys(samples);
    const numSamples = sampleKeys.length;
    const randomSampleNumber = Math.floor(Math.random() * (numSamples - 0));
    //      const randomKey =
    //        sampleKeys[randomSampleNumber];
    sendMidiMessage(instrument.midiChannelName, randomSampleNumber);

    //      source.buffer = samples[`${randomKey}`];
    //      source.connect(gainNode);
    //      source.start();
  }
}
