我正在尝试将android中的流媒体直播到服务器。我的程序运行正常。
开始流式传输的方法是:
private void startStreaming() {
Thread startRecord = new Thread(
new Runnable() {
@Override
public void run() {
try {
socket = new DatagramSocket();
} catch (SocketException e) {
e.printStackTrace();
}
buffer = new byte[minBufSize];
DatagramPacket packet;
try {
destination = InetAddress.getByName("10.31.0.12");
} catch (UnknownHostException e) {
e.printStackTrace();
}
record = new AudioRecord(MediaRecorder.AudioSource.MIC,sampleRate,channelConfig,audioFormat,minBufSize * 10);
record.startRecording();
while ( status )
{
minBufSize = record.read(buffer,0,buffer.length);
packet = new DatagramPacket(buffer,buffer.length,destination,port);
Log.d(LOG,"Writing in status " + destination );
try {
Log.d(LOG, "Trying to send. " + minBufSize);
socket.send(packet);
Log.d(LOG, "Sent successfully.");
} catch (IOException e) {
Log.d(LOG,"Socket is not sending properly.");
e.printStackTrace();
}
}
}
}
);
startRecord.start();
}
停止记录的方法:
public void stopRecording(View view) {
start.setVisibility(View.VISIBLE);
stop.setVisibility(View.GONE);
status = false;
Log.d(LOG,"I am about to release the record.");
record.release();
Log.d(LOG, "I have released.");
}
我正在使用minBufSize
minBufSize = record.read(buffer,0,buffer.length);
如果我继续停止播放录音,
minBufSize
会继续减小。值从1280变为512,从256变为-3,最后我得到:
java.lang.NegativeArraySizeException:-3在
com.example.khan.safevoicerecorder.MainActivity $ 1.run(MainActivity.java:81)
为什么会这样呢?请帮我解决这个问题。
最佳答案
您使用当前的buffer
创建minBufSize
。然后,您的循环读取一会儿:minBufSize = record.read(buffer,0,buffer.length)
。由于读取最多为buffer.length
个字节,因此现在您可以减少minBufSize
了。
下次开始记录时,将使用较小的新minBufSize
创建缓冲区。同样,读取将最多为buffer.length
个字节(现在小于上次)。
冲洗并重复-最终,您将获得一个非常小的缓冲区。我猜这给你-3错误值。最后,当minBufSize
是-3
时,您的buffer
分配将失败;数组不能为负数。