/Users/lyon/j4p/src/sound/audioDigitizer/PlayThread.java
|
1 package sound.audioDigitizer;
2
3 import sound.Utils;
4
5 import javax.sound.sampled.*;
6 import java.io.ByteArrayInputStream;
7 import java.io.ByteArrayOutputStream;
8 import java.io.InputStream;
9
10 /**
11 * Created by IntelliJ IDEA.
12 * User: Douglas Lyon
13 * Date: Dec 14, 2004
14 * Time: 7:06:58 AM
15 * Copyright DocJava, Inc.
16 */
17 public class PlayThread extends Thread {
18 byte tempBuffer[] = new byte[10000];
19 AudioInputStream audioInputStream;
20 SourceDataLine sourceDataLine;
21
22 public PlayThread(AudioInputStream audioInputStream,
23 SourceDataLine sourceDataLine) {
24 this.audioInputStream = audioInputStream;
25 this.sourceDataLine = sourceDataLine;
26
27 }
28
29 public void run() {
30 try {
31 int cnt;
32 //Keep looping until the input
33 // read method returns -1 for
34 // empty stream.
35 while ((cnt = audioInputStream.read(tempBuffer,
36 0, tempBuffer.length)) != -1) {
37 if (cnt > 0) {
38 //Write data to the internal buffer of the data line
39 // where it will be delivered to the speaker.
40
41 sourceDataLine.write(tempBuffer, 0, cnt);
42 }//end if
43 }//end while
44 //Block and wait for internal
45 // buffer of the data line to
46 // empty.
47 sourceDataLine.drain();
48 sourceDataLine.close();
49 } catch (Exception e) {
50 System.out.println(e);
51 System.exit(0);
52 }//end catch
53 }//end run
54
55 public static void playAudio(ByteArrayOutputStream byteArrayOutputStream1) {
56 try {
57 //Get everything set up for playback.
58 //Get the previously-saved data into a byte array object.
59 byte audioData[] = byteArrayOutputStream1.toByteArray();
60 //Get an input stream on the byte array containing the data
61 playAudioData(audioData);
62
63 } catch (Exception e) {
64 System.out.println(e);
65 System.exit(0);
66 }//end catch
67 }//end playAudio
68
69 public static void playAudioData(byte[] audioData) throws LineUnavailableException {
70 InputStream byteArrayInputStream = new ByteArrayInputStream(audioData);
71 AudioFormat audioFormat = Utils.get8khzMono8Format();
72 AudioInputStream audioInputStream = new AudioInputStream(
73 byteArrayInputStream, audioFormat,
74 audioData.length / audioFormat.getFrameSize());
75 DataLine.Info dataLineInfo = new DataLine.Info(
76 SourceDataLine.class, audioFormat);
77 SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
78 sourceDataLine.open(audioFormat);
79 sourceDataLine.start();
80 //Create a thread to play back the data and start it running.
81 // It will run until all the data has been played back.
82 Thread playThread = new Thread(new
83 PlayThread(audioInputStream, sourceDataLine));
84
85 playThread.run();
86 }
87 }//end inner class sound.audioDigitizer.PlayThread
88