📄 record.java
字号:
import javax.sound.sampled.*;
import java.io.*;
import java.util.*;
/**
* Record类
*
* 实现录音功能
*/
class Record implements Runnable
{
private Thread thread;
public byte audioBytes[]; //原始语音数据
public static Clip clip;
public void start()
{
thread = new Thread(this);
thread.setName("Record");
thread.start();
}
public void stop()
{
thread = null;
}
private void shutDown(String message)
{
if (thread != null)
{
thread = null;
Interface.wavMap.repaint();
}
}
public void run()
{
AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 8000, 8,
1, 1, 8000, true); //一个样本是一帧,每秒8000个样本
DataLine.Info info = new DataLine.Info(TargetDataLine.class,format);
TargetDataLine line;
try
{
line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format, line.getBufferSize());
// System.out.println(line.getBufferSize());
}
catch (LineUnavailableException lue)
{
System.out.println(lue.toString());
return;
}
catch (SecurityException se)
{
System.out.println(se.toString());
return;
}
catch (Exception e)
{
System.out.println(e.toString());
return;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
int frameSizeInBytes = format.getFrameSize();
// System.out.println(frameSizeInBytes);
int bufferLengthInFrames = line.getBufferSize() / 8;
// System.out.println(bufferLengthInFrames);
int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes;
// System.out.println(bufferLengthInBytes);
byte[] data = new byte[bufferLengthInBytes];
int numBytesRead=0;
line.start();
// int i=0;
while (thread != null)
{
if((numBytesRead = line.read(data, 0, bufferLengthInBytes)) == -1)
{
break;
}
out.write(data, 0, numBytesRead);
/* System.out.print(i);
System.out.print(":");
System.out.print(data[i]);
System.out.print(" ");
i++;*/
}
line.stop();
line.close();
line = null;
try
{
out.flush();
out.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
byte tempAudioBytes[] = out.toByteArray();
audioBytes=tempAudioBytes;
/* for(int i=0;i<audioBytes.length;i++)
System.out.println(audioBytes[i]);
System.out.println(audioBytes.length);*/
ByteArrayInputStream bais = new ByteArrayInputStream(audioBytes);
AudioInputStream wavStream = new AudioInputStream(bais, format, audioBytes.length / frameSizeInBytes);
AudioFormat wavFormat=wavStream.getFormat();
DataLine.Info info1 = new DataLine.Info(
Clip.class,
wavStream.getFormat(),
((int) wavStream.getFrameLength() * wavFormat.getFrameSize())
);
try
{
clip = (Clip) AudioSystem.getLine(info1);
clip.open(wavStream);
Object currentSound=clip;
}
catch(Exception e)
{
System.out.println(e.toString());
}
try
{
wavStream.reset();
}
catch(Exception e)
{
System.out.println(e.toString());
}
Interface.wavMap.getAudioInputStream(wavStream);
Interface.wavMap.createWaveForm(null);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -