/Users/lyon/j4p/src/sound/audioDigitizer/FilteredAudioInputStream.java

1    package sound.audioDigitizer; 
2     
3    import javax.sound.sampled.AudioFormat; 
4    import javax.sound.sampled.AudioInputStream; 
5    import javax.sound.sampled.AudioSystem; 
6    import javax.sound.sampled.DataLine; 
7    import javax.sound.sampled.LineUnavailableException; 
8    import javax.sound.sampled.SourceDataLine; 
9    import javax.sound.sampled.TargetDataLine; 
10   import java.io.IOException; 
11    
12   /** 
13    * DocJava, Inc. 
14    * http://www.docjava.com 
15    * Programmer: dlyon 
16    * Date: Dec 13, 2004 
17    * Time: 1:21:07 PM 
18    */ 
19   public class FilteredAudioInputStream extends AudioInputStream { 
20       private AudioInputStream ais; 
21       private AudioFormat audioFormat; 
22       private SoundFilter soundFilter; 
23       private static final int REMAINING_SIZE_UNKNOWN = -1; 
24       SourceDataLine sourceDataLine; 
25       TargetDataLine tdl; 
26       public FilteredAudioInputStream(TargetDataLine tdl) { 
27           super(tdl); 
28           AudioFormat audioFormat = tdl.getFormat(); 
29           this.tdl = tdl; 
30       } 
31       public FilteredAudioInputStream(AudioInputStream ais, AudioFormat af, long frameLength, SoundFilter soundFilter) { 
32           super(ais, af, frameLength); 
33           this.soundFilter = soundFilter; 
34           this.ais = ais; 
35           audioFormat = ais.getFormat(); 
36           DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat); 
37           try { 
38               sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo); 
39               sourceDataLine.open(audioFormat); 
40           } catch (LineUnavailableException e) { 
41               e.printStackTrace(); 
42           } 
43       } 
44    
45       public int read(byte[] samples, int offset, int length) 
46               throws IOException { 
47           int remainingSize = length - offset; 
48           int bytesRead = super.read(samples, offset, length); 
49           if (bytesRead > 0) { 
50               soundFilter.filter(samples, offset, bytesRead); 
51               return bytesRead; 
52           } 
53           ; 
54           if (remainingSize == REMAINING_SIZE_UNKNOWN) { 
55               remainingSize = soundFilter.getRemainingSize(); 
56               remainingSize = remainingSize / 4 * 4; 
57           } 
58           ; 
59           if (remainingSize > 0) { 
60               length = Math.min(length, remainingSize); 
61               for (int i = offset; i < offset + length; i++) { 
62                   samples[i] = 0; 
63               } 
64               ; 
65               soundFilter.filter(samples, offset, length); 
66               remainingSize -= length; 
67               return length; 
68           } else { 
69               return -1; 
70           } 
71       } 
72   } 
73