简单总结了下, 就是format, info, line, 把这三个对象获得就可以了.
package com.file;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.management.BadAttributeValueExpException;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;
import javax.sound.sampled.DataLine.Info;
/**
* 测试声音的播放和录制
*/
public class MyAudio
{
public static void main ( String args [] )
{
a1 ();
}
public static void a1 ()
{
// 5秒后要录音停止
Thread t = new StopThread ();
t.start ();
try
{
// format
AudioFormat format = new AudioFormat ( 8000f, 8, 2, true, false );
// info, 使用一次就不用了.
DataLine.Info info = new Info ( TargetDataLine.class, format );
// line
TargetDataLine line = (TargetDataLine) AudioSystem.getLine ( info );
line.open ();
line.start ();
// 长度为 format * line 个位
byte [] buf = new byte [ format.getFrameSize () * line.getBufferSize () / 8 ];
int readBytes = 0;
ByteArrayOutputStream out = new ByteArrayOutputStream ();
while ( recording )
{
readBytes = line.read ( buf, 0, buf.length );
out.write ( buf );
}
line.stop ();
line.close ();
ByteArrayInputStream bais = new ByteArrayInputStream ( out.toByteArray () );
// 三参 = 一参长度 / 二参帧大小
AudioInputStream audioIs = new AudioInputStream ( bais, format
, out.toByteArray ().length / format.getFrameSize () );
AudioSystem.write ( audioIs, AudioFileFormat.Type.WAVE, new File ( "F:/mywav2.wav" ));
// 放音
// format 前面有
// info
DataLine.Info info2 = new Info ( SourceDataLine.class, format );
// line
SourceDataLine line2 = (SourceDataLine ) AudioSystem.getLine ( info2 );
line2.open ();
line2.start ();
readBytes = 0;
audioIs.reset (); // 因为在上面用过一次了, 所以要reset
while ( readBytes != -1 )
{
readBytes = audioIs.read ( buf, 0, buf.length );
line2.write ( buf, 0, readBytes );
}
line2.stop ();
line2.close ();
} catch ( Exception e )
{
e.printStackTrace();
}
}
public static boolean recording = true;
}
class StopThread extends Thread
{
@Override
public void run ()
{
try
{
Thread.sleep ( 5000 );
MyAudio.recording = false;
} catch ( Exception e )
{
// TODO: handle exception
}
}
}