我正在阅读AudioInputStream
并使用它向服务器发出分块POST请求以传输音频。在read()
上调用stop()
和close()
之后,我也不明白为什么流上的TargetDataLine
方法总是返回0。由于流关闭并且没有更多数据(EOF),我预计在某些时候会有-1。这导致我在进行POST的Apache HTTP Client调用中出现问题,因为在某些时候它期望-1终止写入输出流,并且以这种方式永远不会终止写循环。
以下是摘录:
public class MicrophoneTest {
// record duration, in milliseconds
static final long RECORD_TIME = 5000;
private static AudioFormat audioFormat = new AudioFormat(48000, 16, 1, true, false);
public static void main(String[] args) throws URISyntaxException, IOException {
final Microphone recorder = new Microphone(audioFormat);
recorder.open();
// creates a new thread that waits for a specified
// of time before stopping
Thread stopper = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(RECORD_TIME);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
recorder.close();
}
});
stopper.start();
// start recording
AudioInputStream inputStream = recorder.start();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1000];
int read = -1;
while ((read = inputStream.read(buffer)) != -1) {
System.out.println(read);
outputStream.write(buffer);
}
// Never gets here!
}
}
public class Microphone {
private static final Logger LOGGER = LoggerFactory.getLogger(Microphone.class);
// format of audio file
private static final AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;
// the line from which audio data is captured
private TargetDataLine line;
private AudioFormat audioFormat;
public Microphone(AudioFormat audioFormat) {
this.audioFormat = audioFormat;
}
/**
* Prepare the line for recording
*
* @return
*/
public boolean open() {
try {
Info info = AudioSystem.getMixerInfo()[4];
line = (TargetDataLine) AudioSystem.getTargetDataLine(audioFormat, info);
line.open(audioFormat);
} catch (LineUnavailableException ex) {
LOGGER.error(ex.toString(), ex);
return false;
}
return true;
}
/**
* Captures the sound and return the stream
*/
public AudioInputStream start() {
if (line != null) {
line.start(); // start capturing
LOGGER.info("Start recording...");
return new AudioInputStream(line);
// AudioSystem.write(ais, fileType, outputStream);
} else {
throw new IllegalStateException("Line has not created. Cannot start recording");
}
}
/**
* Stops the recording process
*/
public void stop() {
line.stop();
LOGGER.info("Stop recording...");
}
/**
* Closes the target data line to finish capturing and recording *
*/
public void close() {
line.stop();
line.close();
LOGGER.info("Data line closed");
}
}
答案 0 :(得分:1)
麦克风线永远不会到达文件的末尾。无论是打开还是关闭。它不是从磁盘或内存位置读取文件。
我认为您需要将while循环更改为以下内容:
while(isRecording)
{
read = inputStream.read(buffer);
outputStream.write(buffer, 0, read);
}
并让你的stop()方法包括
isRecording = false;
和你的start()方法包括
isRecording = true;
等。那种事。