Issue with the audio tag in LiveView

Hi friends,

I created a simple daily conversational role-playing AI language learning app. I am basically feeding hardcoded prompts and getting chat completion from Anthropic and export that to speech, .mp3 audio file. The issue that I am having is that even though I have provided correct url for ‘src’ in my html audio tag, I cannot play the audo.

Here is my LiveView Heex template.

<div>
  <ul >
    <li :for={response <- @responses}>
      <p><strong>Text:</strong> {response.text}</p>
      <p><strong>Translation:</strong> {response.translation}</p>
      <p><strong>Audio_File_Path:</strong> {response.audio_file_path}</p>
      <audio controls autoplay>
        <source src={response.audio_file_path} type="audio/mpeg" />
      </audio>
    </li>
  </ul>
</div>

And here is my mount and handle_event functions

defmodule MyAppWeb.AudioLive do
  use MyAppWeb, :live_view

  alias MyApp.Services.ConversationService

  @impl true
  def mount(_params, _session, socket) do
    {:ok, assign(socket, :responses, [])}
  end

  @impl true
  def handle_event("start_role_play", %{"scenario" => scenario}, socket) do
    scenario_atom = String.to_atom(scenario)

    case ConversationService.converse(scenario_atom, []) do
      {:ok, response_map} ->
        updated_response = [response_map | socket.assigns.responses]
        {:noreply, assign(socket, :responses, updated_response)}

      {:error, reason} ->
        {:noreply, put_flash(socket, :error, "Conversation failed: #{reason}")}
    end
  end
end

Here is the link to the image of what I have so far.

I would really appreciate any help. Thank you so much.

1 Like

A src of audio/whatever.mp3 will append /audio/whatever.mp3 to the current URL path. How are you serving the file from that location?

Nitpick because it’s a nasty denial-of-service vector: you almost always want String.to_existing_atom or an explicit case, to prevent trouble with too many atoms.

2 Likes

I just realized that I have not implemented the dedicated endpoint for file serving. :man_facepalming:

I believe that is why I am getting this error

[info] GET /audio/1743216642895.mp3
[debug] ** (Phoenix.Router.NoRouteError) no route found for GET /audio/1743216642895.mp3 (MyAppWeb.Router)

Do you have any suggestion or know any resources where I can learn more about serving the file? Thank you so much.

Also, thanks for pointing out about handling too many atoms.

1 Like

The upload guide from Phoenix and Plug.Static:

https://hexdocs.pm/phoenix/1.7.10/file_uploads.html
https://hexdocs.pm/plug/1.14.2/Plug.Static.html

1 Like

Thank you so much for resource. I managed to fix it.

Awesome!