gpt4 book ai didi

java - Android 线程间的数据流

转载 作者:行者123 更新时间:2023-12-01 11:45:31 26 4
gpt4 key购买 nike

我正在尝试在我的 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;
}
}

数据下载正确,但当我查看文件时,它已损坏(某些部分丢失或只是错误)。代码有什么问题吗?是否有可能在线程之间传输整个文件而不会“丢失”?难道不应该吗?我应该重新考虑我的程序的结构吗?也许将所有内容都放在一个线程中?提前致谢...

最佳答案

  1. 代码的线程部分看起来没问题
  2. 是的,应该可以在线程之间传递任意数量的数据
  3. 您可以临时实现单线程代码来过滤排除其他错误的可能性。你可以有一个 FileWriter具有异步和同步实现的接口(interface)。
  4. 我不知道 StreamBuffer 是什么,但我不喜欢这样的事实不同的 StreamBuffer 对象共享相同的数据数组。此代码可能存在错误。

关于java - Android 线程间的数据流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29171844/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com