Oscilloscope.java (2877B)
1 /* 2 * _______ _____ _____ _____ 3 * |__ __| | __ \ / ____| __ \ 4 * | | __ _ _ __ ___ ___ ___| | | | (___ | |__) | 5 * | |/ _` | '__/ __|/ _ \/ __| | | |\___ \| ___/ 6 * | | (_| | | \__ \ (_) \__ \ |__| |____) | | 7 * |_|\__,_|_| |___/\___/|___/_____/|_____/|_| 8 * 9 * ------------------------------------------------------------- 10 * 11 * TarsosDSP is developed by Joren Six at IPEM, University Ghent 12 * 13 * ------------------------------------------------------------- 14 * 15 * Info: http://0110.be/tag/TarsosDSP 16 * Github: https://github.com/JorenSix/TarsosDSP 17 * Releases: http://0110.be/releases/TarsosDSP/ 18 * 19 * TarsosDSP includes modified source code by various authors, 20 * for credits and info, see README. 21 * 22 */ 23 24 25 package be.tarsos.dsp; 26 27 /** 28 * The oscilloscope generates a float array with 29 * array[i] an x coordinate in percentage 30 * array[i+1] the value of the amplitude in audio buffer 31 * array[i+2] another x coordinate in percentage 32 * array[i+3] the next amplitude in the audio buffer 33 * 34 * The implementation is based on the one by Dan Ellis found at http://www.ee.columbia.edu/~dpwe/resources/Processing/ 35 * @author Dan Ellis 36 * @author Joren Six 37 * 38 */ 39 public class Oscilloscope implements AudioProcessor { 40 public static interface OscilloscopeEventHandler{ 41 /** 42 * @param data The data contains a float array with: 43 * array[i] an x coordinate in percentage 44 * array[i+1] the value of the amplitude in audio buffer 45 * array[i+2] another x coordinate in percentage 46 * array[i+3] the next amplitude in the audio buffer 47 * @param event An audio Event. 48 */ 49 void handleEvent(float[] data, AudioEvent event); 50 } 51 float[] dataBuffer; 52 private final OscilloscopeEventHandler handler; 53 public Oscilloscope(OscilloscopeEventHandler handler){ 54 this.handler = handler; 55 } 56 57 @Override 58 public boolean process(AudioEvent audioEvent) { 59 float[] audioBuffer = audioEvent.getFloatBuffer(); 60 int offset = 0; 61 float maxdx = 0; 62 for (int i = 0; i < audioBuffer.length / 4; ++i) { 63 float dx = audioBuffer[i + 1] - audioBuffer[i]; 64 if (dx > maxdx) { 65 offset = i; 66 maxdx = dx; 67 } 68 } 69 70 float tbase = audioBuffer.length / 2; 71 72 73 int length = Math.min((int) tbase, audioBuffer.length-offset); 74 if(dataBuffer == null || dataBuffer.length != length * 4){ 75 dataBuffer = new float[length * 4]; 76 } 77 78 int j = 0; 79 for(int i = 0; i < length - 1; i++){ 80 float x1 = i / tbase; 81 float x2 = i / tbase; 82 dataBuffer[j] = x1; 83 dataBuffer[j+1] = audioBuffer[i+offset]; 84 dataBuffer[j+2] = x2; 85 dataBuffer[j+3] = audioBuffer[i+1+offset]; 86 j = j + 4; 87 } 88 handler.handleEvent(dataBuffer, audioEvent); 89 return true; 90 } 91 92 @Override 93 public void processingFinished() { 94 } 95 96 }