如何解决使用 OkHttp 使用音频流
我想使用 Java 使用以下音频流 - https://playoutonestreaming.com/proxy/bylr?mp=/stream。
主要目标非常简单 - 我想创建一个服务,它允许我目前有 300-400 个活动连接(例如活动侦听器)。当我尝试与 OkHttp 建立连接时出现问题。
这是我的代码:
- 使用流的任务
@Slf4j
@RequiredArgsConstructor
class ListenStream implements Runnable {
private static final String STREAM_URL = "https://playoutonestreaming.com/proxy/bylr?mp=/stream";
private final OkHttpClient client;
private final int id;
@Override
public void run() {
Clip clip;
try {
log.info("[TASK-{}] - Connecting to the stream...",id);
Request request = new Request.Builder()
.url(STREAM_URL)
.get()
.build();
Response response = client.newCall(request).execute();
assert response.body() != null;
InputStream is = new ByteArrayInputStream(response.body().bytes());
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(is);
clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.loop(Clip.LOOP_CONTINUOUSLY);
} catch (IOException e) {
log.info("Finished listening to the stream");
} catch (LineUnavailableException | UnsupportedAudioFileException e) {
log.error("Failed to process audio stream");
e.printStackTrace();
}
}
}
- 执行者
public class RadioMain {
public static void main(String[] args) throws InterruptedException {
OkHttpClient client = new OkHttpClient.Builder()
.callTimeout(120,TimeUnit.SECONDS)
.connectTimeout(120,TimeUnit.SECONDS)
.readTimeout(120,TimeUnit.SECONDS)
.writeTimeout(120,TimeUnit.SECONDS)
.followRedirects(true)
.followSslRedirects(true)
.build();
ExecutorService service = Executors.newFixedThreadPool(300);
List<Runnable> tasks = IntStream.range(1,301)
.mapToObj(number -> new ListenStream(client,number))
.collect(Collectors.toList());
tasks.forEach(service::submit);
service.awaitTermination(120,TimeUnit.SECONDS);
service.shutdown();
}
}
使用以下方法,我必须为 OkHttpClient 设置超时,然后使用它发出请求。但是,一旦出现超时,我就会收到一个 InterruptedIOException: socket closed
,我需要创建一个新任务。
是否有使用 OkHttp 使用音频流的正确方法?
解决方法
在该时间长度后,调用超时将使请求失败,因此请删除该设置或将其定义为 0。
https://square.github.io/okhttp/4.x/okhttp/okhttp3/-ok-http-client/-builder/call-timeout/
设置完整调用的默认超时时间。值 0 表示没有 超时,否则值必须介于 1 和 Integer.MAX_VALUE 之间 转换为毫秒。
呼叫超时跨越整个呼叫:解析 DNS、连接、 写入请求正文、服务器处理和读取响应 身体。如果调用需要重定向或重试都必须完成 在一个超时时间内。
默认值为 0,表示没有超时。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。