作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试在我的 Android 应用程序中实现流音频,所以我想要做的是在一个线程中从 http 服务器下载音频文件并将其发送到第二个线程进行解码。为了将流从第一个线程发送到第二个线程,我尝试使用不同类型的 BlockingQueues 甚至 PipedReader 和 PipedWriter (但它们非常非常慢)。为了测试线程之间的通信,我只是将数据写入第二个线程中的文件,而不是解码 mp3 数据。
这两个线程由主线程产生(下载线程实际上是一个 AsyncTask)。
这是队列,在主线程中最终创建: 最终 BlockingQueue 流 = new LinkedBlockingQueue();
AsyncTask的doInBackground():
InputStream input = null;
HttpURLConnection connection = null;
try {
URL url = new URL("http://" + serverIP + "/songs/test.mp3");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
input = connection.getInputStream();
byte data[] = new byte[CHUNK_SIZE];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
stream.put(new StreamBuffer(data, count));
}
} catch (Exception e) {
return -1;
} finally {
try {
if (output != null) output.close();
if (input != null) input.close();
} catch (Exception e) {
}
if (connection != null)
connection.disconnect();
}
线程2的run():
try {
FileOutputStream outputnf = null;
try {
outputnf = new FileOutputStream(Environment.getExternalStorageDirectory() + "/CCMP/test.mp3");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (true) {
StreamBuffer buff = ((StreamBuffer) stream.take());
if (outputnf != null) {
outputnf.write(buff.buffer, 0, buff.length);
}
}
} catch (Exception e) {
System.out.println(" PipeThread Exception: " + e);
}
流缓冲区:
public class StreamBuffer
{
byte[] buffer;
int length;
public StreamBuffer(byte[] data, int count) {
buffer = data;
length = count;
}
}
数据下载正确,但当我查看文件时,它已损坏(某些部分丢失或只是错误)。代码有什么问题吗?是否有可能在线程之间传输整个文件而不会“丢失”?难道不应该吗?我应该重新考虑我的程序的结构吗?也许将所有内容都放在一个线程中?提前致谢...
最佳答案
关于java - Android 线程间的数据流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29171844/
我是一名优秀的程序员,十分优秀!