Audio streaming gives an error while using Elixir Req

There’s a python/fastapi service that streams audio files. I don’t have access to the code of this service.

This works fine and the audio can be played.

<audio controls src="some/audio/url">
    Your browser does not support the <code>audio</code> element.
</audio>

This one doesn’t

Mix.install([
  {:req, "~> 0.4.0"}
])
url = "some/audio/url"

Req.get!(url, into: IO.stream())
|> Stream.each(&IO.inspect/1)
|> Stream.run()

The following error is thrown

** (ArgumentError) errors were found at the given arguments:

  * 2nd argument: not valid character data (an iodata term)

    (stdlib 4.0.1) io.erl:99: :io.put_chars(:standard_io, <<0, 0, 0, 24, 102, ...>>)
    (req 0.4.5) lib/req/steps.ex:760: anonymous fn/3 in Req.Steps.finch_stream_into_collectable/5
    (finch 0.16.0) lib/finch/http1/conn.ex:231: Finch.Conn.receive_response/8
    (finch 0.16.0) lib/finch/http1/conn.ex:120: Finch.Conn.request/6
    (finch 0.16.0) lib/finch/http1/pool.ex:45: anonymous fn/8 in Finch.HTTP1.Pool.request/5
    (nimble_pool 1.0.0) lib/nimble_pool.ex:349: NimblePool.checkout!/4
    (finch 0.16.0) lib/finch/http1/pool.ex:38: Finch.HTTP1.Pool.request/5

What am I missing?

By default, IO.stream is expecting to read and write UTF8-shaped byte sequences.

Raw audio data is definitely not that.

You likely want IO.binstream, though connecting that to an already-open stdio may need additional code.

2 Likes

Yes. That makes sense. Thanks!