[SOLVED] How to add an javascript file that is staticaly served (for an AudioWorkletNode)

Hi,
I am trying to use phoenix for a project, where I use AudioWorkletNode or Processing input audio from the Microphone.

I am new to phoenix as well as loading audio from the Microphone in the browser.

If I understand the AudioWorkletNode Dokumentation here correctly, I habe to put my Audio Processing class into its own file.

How do I do that in Phoenix?
I tried adding a javascript file to assets/js/audio_worklet.js but I am unable to load it.

Can I somehow tell Phoenix, that that is a static file and it should serve it as is? Or what would be a better way of doing this here?

Thanks!

I got, you can add the file to the static files. In my case I have a phoenix starter template, and i could add the file to priv/static/js/audio_worklet.js.
Then I only had to make the js directory known, which I did by adding js to the static_paths defined in `<my_app>_web.ex:

  def static_paths, do: ~w(assets fonts images js favicon.ico robots.txt)

assets/js/audio_worklet.js is the right place if you want it to be built, bundled, minified, and used along with all of your other JS. You were just missing one step which is to import it in assets/app.js (which is the entry point for esbuild configured in config/config.exs).

Otherwise, if you specifically don’t want it built and want to use it with a <script> tag then what you have done is correct.

Thanks for the clarifaction, I indeed believe I have to use it as an “js” resource outside of my main Javascript to use it with AudioWorkletNode.

You can definitely bundle if you want:

// assets/js/my_audio.js

class MyAudio {
  // ...
}

export default MyAudio
// assets/app.js

import MyAudio from "./js/audio"

If you’re using LiveView this is the better option as it can be used with JS Hooks but if you’re using controllers then you’re probably all good. Up to you, of course!

In case you want to server it as a separate file from your app (to reduce the size of app.js file) you can bundle it separately, then build it with esbuild audio

# * Config example is from older project
# file "config.exs"
config :esbuild,
  version: "0.14.41",
  default: [
    args:
      ~w(js/app.js --bundle --target=es2017 --outdir=../priv/static/assets --external:/fonts/* --external:/images/*),
    cd: Path.expand("../assets", __DIR__),
    env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)}
  ],
  audio: [
    args:
      ~w(js/audio.js --bundle --target=es2017 --outdir=../priv/static/assets --external:/fonts/* --external:/images/* --sourcemap --minify),
    cd: Path.expand("../assets", __DIR__),
    env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)}
  ]

With file being located at “js/audio.js”, you can update this to your preference just update name in config

1 Like