我想将硬盘用作音频信号的缓冲区。我的想法是将字节形式的样本写入文件,并用另一个线程读取相同的内容。但是,我不得不问FIS.read(byte[]);
返回0并给我一个空缓冲区。
这里有什么问题?
这是我写字节的操作:
try {
bufferOS.write(audioChunk);
bufferOS.flush();
} catch (IOException ex) {
//...
}
这就是我的读者所做的:
byte audioChunk[] = new byte[bufferSize];
int readBufferSize;
int freeBufferSize = line.available(); // line = audioline, available returns free space in buffer
try {
readBufferSize = bufferIS.read(audioChunk,freeBufferSize, 0);
} catch(IOException e) {
//...
}
我使用相同的文件创建bufferOS
和bufferIS
,两者都有效
作者工作,创建文件并在其中包含正确的数据
但是,bufferIS.read();
- 来电始终会返回0
fileInputStream
使用buffer.available();
返回正确的可用字节数,freeBufferSize
和audioChunk.length
等参数是正确的。
在Windows中的同一文件上运行FileInputStream
和FileOutputStream
是否有问题?
答案 0 :(得分:2)
您以错误的顺序将参数传递给read
来电,应该是:
readBufferSize = bufferIS.read(audioChunk, 0, freeBufferSize);
现在您正在传递freeBufferSize
作为偏移量来存储read
调用的结果,0
作为最大读取的字节数。毫不奇怪,如果你告诉read
调用最多读取零字节,那么它返回它已读取零字节。
的Javadoc:
* @param b the buffer into which the data is read. * @param off the start offset in array <code>b</code> * at which the data is written. * @param len the maximum number of bytes to read. * @return the total number of bytes read into the buffer, or * <code>-1</code> if there is no more data because the end of * the stream has been reached.
public abstract class InputStream implements Closeable {
// ....
public int read(byte b[], int off, int len) throws IOException