User Tools

Site Tools


cs276:normalize
/*
 * Normalize
 *
 * Normalizes a sound file by computing a "normalization factor" based on the max amplitude
 * in the sample buffer, then multiplying every sample in the buffer by this factor.
 * 
 * Press 1 to play the original sound, 2 to play the normalized sound
 *
 * Created Krister Olssen/spc, last modified 06 November 2019
 */
 
import processing.sound.*;
 
SoundFile myChannel, myCopy;
 
void setup() {
  size(256, 200);
  background(0, 0, 255);
 
  // load "cell.aif" into a new SoundFile
  myChannel = new SoundFile(this, "thisisatest.wav");
  myCopy = new SoundFile(this, "thisisatest.wav");
  normalize(myChannel);
 
  noLoop();
}
 
float maxSample(float[] samples) {
  float largest = 0;
  for (int i = 0; i < samples.length; i++) {
    float absolute = abs(samples[i]);
    if (largest < absolute)
      largest = absolute;
  }
  return largest;
}
 
void normalize(AudioSample chan) {
  float largest;
  float[] samples = new float [chan.frames()];
 
  // read samples from AudioSample into samples array
  chan.read(samples);
 
  // find the largest amplitude in the sample buffer
  largest = maxSample(samples);
  println(largest);
 
  // compute a multiplier
  float mult = 1.0 / largest;
 
  // apply the multiplier to every sample
  for (int i = 0; i < samples.length; i++) {
    samples[i] *= mult;
  }
 
  // write the samples back into the sample buffer
  chan.write(samples);
}
 
void keyPressed() {
  if (key == '1') {
    myCopy.play();
  } else if (key == '2') {
    myChannel.play();
  }
}
 
void draw() {
  int size = myCopy.frames();
  float[] samples = new float [size];
  myCopy.read(samples);
 
  // draw each sample (as many as the window can hold)
  for (int i = 0; i < size; i++) {
    set(i, (int)(100 + samples[i] * 100), 0);
  }
}
cs276/normalize.txt · Last modified: 2019/11/06 20:55 by scarl