lundi 26 novembre 2018

Javascript - retrieve random image from array

I'm trying to write a program using Javascript and the p5.js library to trigger a random image from an array whenever a peak in an audio file is detected. p5's sound library can detect the audio peak for me and then trigger a function upon that audio peak. However, I don't have much experience in Javascript so I'm not sure where to go from here. I've created an array of images and am planning on creating a function using math.Random to grab one of these images. Can I then call that function within my triggerBeat function?

Also, I've set the image as the background so that it's not within p5's draw function, so I'm trying to change the bg variable. I've preloaded the background image, and I've also got code within the preload function to allow the user to upload an audio file.

Sorry if this doesn't make a ton of sense. I'm pretty new to Javascript and I've spent most of today trying to wrap my head around it.

var cnv, song, fft, peakDetect, img, bg;

var imageset = new Array;
imageset[0] = "dogs01.png";
imageset[1] = "dogs02.png";
imageset[2] = "dogs03.png";
imageset[3] = "dogs04.png";
imageset[4] = "dogs05.png";
imageset[5] = "dogs06.png";
imageset[6] = "dogs07.png";
imageset[7] = "dogs08.png";
imageset[8] = "dogs09.png";
imageset[9] = "dogs10.png";
imageset[10] = "dogs11.png";
imageset[11] = "dogs12.png";
imageset[12] = "dogs13.png";
imageset[13] = "dogs14.png";
imageset[14] = "dogs15.png";
imageset[15] = "dogs16.png";
imageset[16] = "dogs17.png";
imageset[17] = "dogs18.png";
imageset[18] = "dogs19.png";
imageset[19] = "dogs20.png";
imageset[20] = "dogs21.png";
imageset[21] = "dogs22.png";
imageset[22] = "dogs23.png";
imageset[23] = "dogs24.png";
imageset[24] = "dogs25.png";

function preload(){
  img = loadImage("dogs01.png");
  var loader = document.querySelector(".loader");
  document.getElementById("audiofile").onchange = function(event) {
      if(event.target.files[0]) {
          if(typeof song != "undefined") {
              song.disconnect();
              song.stop();
          }


          song = loadSound(URL.createObjectURL(event.target.files[0]));
          loader.classList.add("loading");
      }
  }
}


function setup() {
  bg = loadImage("dogs01");
  cnv = createCanvas(200,154);

  fft = new p5.FFT();
  peakDetect = new p5.PeakDetect();

  setupSound();
  peakDetect.onPeak(triggerBeat);
}

function draw() {
  background(bg);

  fill(0);
  text('play', width/2, height/2);

  fft.analyze();
  peakDetect.update(fft);


}

function triggerBeat() {

//this is where I want an image to be pulled from the array and randomly displayed

}


function setupSound() {
  cnv.mouseClicked( function() {
    if (song.isPlaying() ) {
      song.stop();
    } else {
      song.play();
    }
  });
}




Aucun commentaire:

Enregistrer un commentaire