plectrum

Plectrum: instrument tuner for Android
Log | Files | Refs | README | LICENSE

WriterProcessor.java (1980B)


      1 package be.tarsos.dsp.writer;
      2 
      3 
      4 import java.io.ByteArrayOutputStream;
      5 import java.io.IOException;
      6 import java.io.RandomAccessFile;
      7 
      8 import be.tarsos.dsp.AudioEvent;
      9 import be.tarsos.dsp.AudioProcessor;
     10 import be.tarsos.dsp.io.TarsosDSPAudioFormat;
     11 
     12 /**
     13  * This class writes the ongoing sound to an output specified by the programmer
     14  *
     15  */
     16 public class WriterProcessor implements AudioProcessor {
     17     RandomAccessFile output;
     18     TarsosDSPAudioFormat audioFormat;
     19     private int audioLen=0;
     20     private  static final int HEADER_LENGTH=44;//byte
     21 
     22     /**
     23      *
     24      * @param audioFormat which this processor is attached to
     25      * @param output randomaccessfile of the output file
     26      */
     27     public WriterProcessor(TarsosDSPAudioFormat audioFormat,RandomAccessFile output){
     28         this.output=output;
     29         this.audioFormat=audioFormat;
     30         try {
     31             output.write(new byte[HEADER_LENGTH]);
     32         } catch (IOException e) {
     33             e.printStackTrace();
     34         }
     35     }
     36     @Override
     37     public boolean process(AudioEvent audioEvent) {
     38         try {
     39             audioLen+=audioEvent.getByteBuffer().length;
     40             //write audio to the output
     41             output.write(audioEvent.getByteBuffer());
     42         } catch (IOException e) {
     43             e.printStackTrace();
     44         }
     45         return true;
     46     }
     47 
     48     @Override
     49     public void processingFinished() {
     50         //write header and data to the result output
     51         WaveHeader waveHeader=new WaveHeader(WaveHeader.FORMAT_PCM,
     52                 (short)audioFormat.getChannels(),
     53                 (int)audioFormat.getSampleRate(),(short)16,audioLen);//16 is for pcm, Read WaveHeader class for more details
     54         ByteArrayOutputStream header=new ByteArrayOutputStream();
     55         try {
     56             waveHeader.write(header);
     57             output.seek(0);
     58             output.write(header.toByteArray());
     59             output.close();
     60         }catch (IOException e){
     61             e.printStackTrace();
     62         }
     63 
     64     }
     65 }