Posted on 2009-06-09 11:08
java人生 阅读(1337)
评论(0) 编辑 收藏
由于项目中有关于java录音的东西,所以从网上找些资料学习一下
1import java.io.*;
2import javax.sound.sampled.*;
3
4public class JDKAudioRecorder extends Thread {
5 // 產生TargetDataLine類別的變數m_targetdataline
6 static TargetDataLine m_targetdataline;
7
8 // 透過TargetDataLine介面(繼承自DataLine)與音效卡溝通 target目標
9
10 // 產生AudioFileFormat.Type類別的變數m_targetType Format格式
11 static AudioFileFormat.Type m_targetType;
12
13 // 產生AudioInputStream類別的變數m_audioInputStream stream流
14 static AudioInputStream m_audioInputStream;
15
16 static File m_outputFile;// 產生File類別的變數 m_outputFile
17
18 static boolean m_bRecording;// 後面需用到布林函數 True,False
19
20 public JDKAudioRecorder(TargetDataLine line,
21 AudioFileFormat.Type targetType, File file) {
22 m_targetdataline = line;
23 m_audioInputStream = new AudioInputStream(line);
24 m_targetType = targetType;
25 m_outputFile = file;
26 }
27
28 public static void AudioRecorder() {
29 String Filename = "c://JDKAudioRecord.wav";
30 File outputFile = new File(Filename);
31
32 // 我們一開始先在主程式裡指定聲音檔的檔名為
33 // JDKAudioRecorder.wav
34 // String Filename = "JDKAudioRecord.wav";
35 // 接著指定存檔的資料夾,預設存在相同的資料夾
36 // FileoutputFile = new File(Filename);
37
38 AudioFormat audioFormat = null;
39 audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
40 44100.0F, 16, 2, 4, 44100.0F, false);
41
42 // 再來設定和取得音效檔的屬性
43 // audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
44 // 44100.0F, 16, 2, 4, 44100.0F, false);
45
46 DataLine.Info info = new DataLine.Info(TargetDataLine.class,
47 audioFormat);
48 TargetDataLine targetDataLine = null;
49
50 // 然後透過TargetDataLine介面(繼承自DataLine)與音效卡溝通
51 // DataLine.Info info = new DataLine.Info(TargetDataLine.class,
52 // audioFormat);
53 // 接著做例外處理,當聲音裝置出錯或其他因素導致錄音功能無法被執行時,程式將被終止
54
55 try {
56 targetDataLine = (TargetDataLine) AudioSystem.getLine(info);
57 targetDataLine.open(audioFormat);// try{ }可能發生例外的敘述
58
59 } catch (LineUnavailableException e)// catch{ }處理方法
60
61 {
62 System.out.println("無法錄音,錄音失敗");
63 e.printStackTrace();
64 System.exit(-1);
65 }
66
67 AudioFileFormat.Type targetType = AudioFileFormat.Type.AU;
68 JDKAudioRecorder recorder = null;
69
70 recorder = new JDKAudioRecorder(targetDataLine, targetType, outputFile);
71 recorder.start();
72 }
73
74 public void start() {
75 m_targetdataline.start();
76 super.start();
77 }
78
79 public static void stopRecording() {
80
81 m_targetdataline.stop();
82 m_targetdataline.close();
83 m_bRecording = false;
84 }
85
86 public void run() {
87 try {
88 AudioSystem.write(m_audioInputStream, m_targetType, m_outputFile);
89 System.out.println("after write()");
90 } catch (IOException e) {
91 e.printStackTrace();
92 }
93 }
94
95}
96// 一切準備ok後,開始呼叫DataLine類別中的start()method即可
97// 開始錄音,停止錄音則透過stopRecording()method
98// public void start()
99//{
100//m_targetdataline.start();
101//}
102// public static void stopRecording()
103//{
104//m_targetdataline.stop();
105//}
106