簡體   English   中英

使用 OkHttp 消費音頻 stream

[英]Consuming the audio stream with OkHttp

我想使用 Java - https://playoutonestreaming.com/proxy/bylr?mp=/stream使用以下音頻 stream

主要目標非常簡單——我想創建一個服務,它允許我目前擁有 300-400 個活動連接(例如活動偵聽器)。 當我嘗試與 OkHttp 建立連接時出現問題。

這是我的代碼:

  1. 使用 stream 的任務
@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();
        }
    }
}
  1. 執行者
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 使用音頻 stream 的正確方法?

調用超時將在該時間長度后使請求失敗,因此刪除該設置或將其定義為 0。

https://square.github.io/okhttp/4.x/okhttp/okhttp3/-ok-http-client/-builder/call-timeout/

設置完整調用的默認超時。 值 0 表示沒有超時,否則轉換為毫秒時,值必須介於 1 和 Integer.MAX_VALUE 之間。

調用超時跨越整個調用:解析 DNS、連接、寫入請求體、服務器處理和讀取響應體。 如果調用需要重定向或重試,所有都必須在一個超時期限內完成。

默認值為 0,表示沒有超時。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM