Could we imagine a live_audio_preview and live_video_preview like live_img_preview?

I would like to preview audio and video on the web page using resp. audio and video elements. I saw that the live_img_preview component put a special img element with a data-phx-hook="Phoenix.LiveImgPreview" and that LiveImgPreview does its magic using LiveUploader in JS. I have two questions:

  1. Is it going to be included in Phoenix LiveView ? :slight_smile:
  2. How could I put my own elements with the right src attribute easily ? I could write a LiveAudioPreview which calls LiveUploader just like LiveImgPreview but it looks like the object is encapsulated through an IIFE, making things difficult without a lot of hacking IMHO.

Another way would be to directly upload the files onto the server which would allow me to get an URL pointing to a file like in the nice examples by @mcrumm at GitHub - mcrumm/live_upload_example: Demonstrating file uploads with Phoenix LiveView with auto_upload: true (files: auto.ex and auto.html.heex). But it is not as nice as a preview before uploading.

1 Like

Given an upload with the name videos @uploads.videos (You could use a hook as well if you wanted)

You could also add the controls attribute if you wanted to watch the video, not just have a static preview.

<video-preview :if={@entry} ref={@entry.ref} id={"video_preview_#{@entry.ref}"} phx-update="ignore">
  <video><source /></video>
  class VideoPreview extends HTMLElement {
    connectedCallback() {
      const ref = this.getAttribute("ref");
      const input = document.querySelector('input[type="file"][name="videos"]');
      const files = input.phxPrivate.files;
      const file = files.find((e) => e._phxRef == ref);
      const source = this.querySelector("source");
      source.setAttribute("src", URL.createObjectURL(file));

Thanks. You made my day. It is working well and simplifies the code. I will do the same for the audio.

1 Like