summaryrefslogtreecommitdiff
path: root/songdbj/de/jarnbjo/util/audio/FadeableAudioInputStream.java
blob: 4916102d4b26f79cbbb724baa5fad32e815b117e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package de.jarnbjo.util.audio;

import java.io.*;
import javax.sound.sampled.*;

public class FadeableAudioInputStream extends AudioInputStream {

   private AudioInputStream stream;
   private boolean fading=false;
   private double phi=0.0;

   public FadeableAudioInputStream(AudioInputStream stream) throws IOException {
      super(stream, stream.getFormat(), -1L);
   }

   public void fadeOut() {
      fading=true;
      phi=0.0;
   }

   public int read(byte[] b) throws IOException {
      return read(b, 0, b.length);
   }

   public int read(byte[] b, int offset, int length) throws IOException {
      int read=super.read(b, offset, length);

      //System.out.println("read "+read);

      if(fading) {
         int j=0, l=0, r=0;
         double gain=0.0;

         for(int i=offset; i<offset+read; i+=4) {
            j=i;
            l=((int)b[j++])&0xff;
            l|=((int)b[j++])<<8;
            r=((int)b[j++])&0xff;
            r|=((int)b[j])<<8;

            if(phi<Math.PI/2) {
               phi+=0.000015;
            }

            gain=Math.cos(phi);
            //System.out.println("gain "+gain);

            l=(int)(l*gain);
            r=(int)(r*gain);

            j=i;
            b[j++]=(byte)(l&0xff);
            b[j++]=(byte)((l>>8)&0xff);
            b[j++]=(byte)(r&0xff);
            b[j++]=(byte)((r>>8)&0xff);
         }
      }

      return read;
   }

}