gpt4 book ai didi

java - 使用 Java 的 HTTP Post Jersey 中的音频文件流

转载 作者:行者123 更新时间:2023-11-30 11:17:20 24 4
gpt4 key购买 nike

在过去的几天里,我一直被一个问题所困扰,坦率地说,我没有想法。我想做的是使用 Jersey 托管一个休息服务,该服务将接受在其有效负载中包含音频数据流的发布请求。

我遇到的问题是我失去了数据一致性(我在客户端和服务器上都运行 CRC 检查)并且在使用 1024 字节缓冲区读取 8 次之后,发送数据和接收数据之间的 CRC 变得不一致。当我处理文本或较小尺寸的内容时,它工作得很好。附上代码,谁能告诉我我做错了什么?

服务器:

@POST
@Consumes("audio/wav")
@Produces(MediaType.TEXT_PLAIN)
public String streamCommand(@Context HttpServletRequest request ) throws Exception
{
CRC32 crc = new CRC32();
InputStream stream = request.getInputStream();
byte[] readBuffer = new byte[1024];
StringBuilder builder = new StringBuilder();
while (stream.read(readBuffer) > -1)
{
crc.update(readBuffer);
builder.append(new String(readBuffer));
System.out.println(crc.getValue());
}

return builder.toString();
}

客户:

static final String SOUND_FILE_NAME = "SoundTest.wav";

@BeforeClass
public static void setup() throws Exception
{
soundStream = classloader.getResourceAsStream(SOUND_FILE_NAME);
}

@Test
public void test() throws Exception {

PipedOutputStream stream = new PipedOutputStream();

DataStreamer data = new DataStreamer(stream, soundStream);
ExecutorService executor = Executors.newFixedThreadPool(1);

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://localhost:8080/EVAFrontEnd/webapi/users/1/devices/1/command");
post.addHeader(HttpHeaders.CONTENT_TYPE, "audio/wav");

InputStreamEntity requestEntity = new InputStreamEntity(new PipedInputStream((PipedOutputStream) stream), -1);
post.setEntity(requestEntity);

executor.execute(data);
executor.shutdown();

HttpResponse r = client.execute(post);
assertNotNull(r);

}

数据流:

public class DataStreamer implements Runnable {

OutputStream writeStream;
CheckedInputStream readStream;
static Logger logger = Logger.getLogger(DataStreamer.class);

public DataStreamer(OutputStream stream, InputStream readingStrem) {
this.writeStream = stream;
this.readStream = new CheckedInputStream(readingStrem, new Adler32());
}

@Override
public void run()
{
CRC32 crc = new CRC32();
try {
byte[] buffer = new byte[1024];
while (readStream.read(buffer) > -1) {
crc.update(buffer);
System.out.println(crc.getValue());
writeStream.write(buffer);
}

System.out.println("END CRC");
readStream.close();
writeStream.close();
}
catch (Exception e) {
logger.error("Unable to stream data.", e);
}
}
}

谢谢!

最佳答案

你需要一直保存写入的字节数

bytes_read = readStream.read(buffer);

到一个变量中,因为该方法有时会给出一个简短的结果。然后使用 ArrayList.copyOfRange 从缓冲区创建一个仅包含有效字节的子数组 [0 ... bytes_read-1] 。

关于java - 使用 Java 的 HTTP Post Jersey 中的音频文件流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24404296/

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