用Java录音
在application中,要如何实现Java的录音啊。
程序运行在linux环境中。
有做过类似的功能的兄弟,给个例子。谢过了。
------解决方案--------------------JMF 实现,音频传输都没问题,去SUN网站研究下吧
------解决方案--------------------没做过,up
------解决方案--------------------import java.io.*;
import javax.sound.sampled.*;
import javax.sound.sampled.spi.*;//前置處理
public class JDKAudioRecorder extends Thread
{
//產生TargetDataLine類別的變數m_targetdataline
static TargetDataLine m_targetdataline;
//透過TargetDataLine介面(繼承自DataLine)與音效卡溝通 target目標
//產生AudioFileFormat.Type類別的變數m_targetType Format格式
static AudioFileFormat.Type m_targetType;
//產生AudioInputStream類別的變數m_audioInputStream stream流
static AudioInputStream m_audioInputStream;
static File m_outputFile;//產生File類別的變數 m_outputFile
static boolean m_bRecording;//後面需用到布林函數 True,False
public JDKAudioRecorder(TargetDataLine line, AudioFileFormat.Type targetType, File file)
{
m_targetdataline = line;
m_audioInputStream = new AudioInputStream(line);
m_targetType = targetType;
m_outputFile = file;
}
public static void AudioRecorder()
{
String Filename = "JDKAudioRecord.wav ";
File outputFile = new File(Filename);
//我們一開始先在主程式裡指定聲音檔的檔名為
//JDKAudioRecorder.wav
// String Filename = "JDKAudioRecord.wav ";
//接著指定存檔的資料夾,預設存在相同的資料夾
// File outputFile = new File(Filename);
AudioFormat audioFormat = null;
audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100.0F, 16, 2, 4, 44100.0F, false);
//再來設定和取得音效檔的屬性
// audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100.0F, 16, 2, 4, 44100.0F, false);
DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat);
TargetDataLine targetDataLine = null;
//然後透過TargetDataLine介面(繼承自DataLine)與音效卡溝通
// DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat);
// 接著做例外處理,當聲音裝置出錯或其他因素導致錄音功能無法被執行時,程式將被終止
try
{
targetDataLine = (TargetDataLine) AudioSystem.getLine(info);
targetDataLine.open(audioFormat);// try{ }可能發生例外的敘述
} catch (Line
UnavailableException e)//catch{ }處理方法
{
System.out.println( "無法錄音,錄音失敗 ");
e.printStackTrace();
System.exit(-1);
}
AudioFileFormat.Type targetType = AudioFileFormat.Type.AU;
JDKAudioRecorder recorder = null;
recorder = new JDKAudioRecorder(targetDataLine, targetType, outputFile);
recorder.start();
}
public void start()
{
m_targetdataline.start();
super.start();
}
public static void stopRecording()
{
m_targetdataline.stop();
m_targetdataline.close();
m_bRecording = false;
}
public void run()
{
try
{
AudioSystem.write(m_audioInputStream, m_targetType, m_outputFile);
System.out.println( "after write() ");
} catch (
IOException e)
{
e.printStackTrace();
}
}
}
//一切準備ok後,開始呼叫DataLine類別中的start()method即可
//開始錄音,停止錄音則透過stopRecording()method
// public void start()
//{
// m_targetdataline.start();
//}
// public static void stopRecording()
//{
// m_targetdataline.stop();
//}