HaarWaveletFileWriter.java (2825B)
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 package be.tarsos.dsp.wavelet; 25 26 import java.io.FileNotFoundException; 27 import java.io.FileOutputStream; 28 import java.io.IOException; 29 30 import be.tarsos.dsp.AudioEvent; 31 import be.tarsos.dsp.AudioProcessor; 32 33 public class HaarWaveletFileWriter implements AudioProcessor { 34 35 36 private final int compression; 37 private FileOutputStream rawOutputStream; 38 39 public HaarWaveletFileWriter(String fileName, int compression){ 40 this.compression = compression; 41 try { 42 this.rawOutputStream = new FileOutputStream(fileName); 43 } catch (FileNotFoundException e) { 44 this.rawOutputStream = null; 45 } 46 } 47 48 @Override 49 public boolean process(AudioEvent audioEvent) { 50 float[] audioBuffer = audioEvent.getFloatBuffer(); 51 52 int placesWithZero = 0; 53 int zeroCounter = 0; 54 for(int i = 0 ; i < audioBuffer.length ; i++){ 55 if(audioBuffer[i]==0 && zeroCounter < compression){ 56 zeroCounter++; 57 placesWithZero = placesWithZero | (1<<i); 58 } 59 } 60 61 assert zeroCounter == compression; 62 63 64 //16 bits little endian 65 byte[] byteBuffer = new byte[(audioBuffer.length - compression) * 2]; 66 zeroCounter = 0; 67 int bufferIndex = 0; 68 for (int i = 0; i < byteBuffer.length; i++) { 69 float value = audioBuffer[bufferIndex++]; 70 if(value == 0 && zeroCounter < compression ){ 71 zeroCounter++; 72 i--; 73 } else{ 74 int x = (int) (value * 32767.0); 75 byteBuffer[i] = (byte) x; 76 i++; 77 byteBuffer[i] = (byte) (x >>> 8); 78 } 79 } 80 81 try { 82 rawOutputStream.write(byteBuffer); 83 rawOutputStream.write((byte) placesWithZero); 84 rawOutputStream.write((byte) (placesWithZero>>>8)); 85 rawOutputStream.write((byte) (placesWithZero>>>16)); 86 rawOutputStream.write((byte) (placesWithZero>>>24)); 87 88 } catch (IOException e) { 89 e.printStackTrace(); 90 } 91 92 93 return true; 94 } 95 96 @Override 97 public void processingFinished() { 98 try { 99 rawOutputStream.close(); 100 } catch (IOException e) { 101 // TODO Auto-generated catch block 102 e.printStackTrace(); 103 } 104 105 } 106 107 }