Embedding audio with Hugo shortcodes

An audio player only needs a few lines of HTML, but repeating those lines in Markdown gets tedious. A Hugo shortcode keeps the markup in one place and gives each post a much cleaner way to embed an MP3.

Create layouts/shortcodes/audio.html:

<figure {{ with .Get "class" }}class="{{ . }}"{{ end }}>
  <audio controls preload="{{ .Get "preload" | default "metadata" }}">
    {{ with .Get "src" }}<source src="{{ . | relURL }}" type="audio/mpeg">{{ end }}
  </audio>
  {{ with .Get "caption" }}<figcaption>{{ . }}</figcaption>{{ end }}
</figure>

Then use it in a content file:

{ { < audio src="/audio/file.mp3" caption="Caption" > } }

The shortcode accepts a source URL, an optional caption, and an optional CSS class. It also defaults preload to metadata, so the browser can read details such as the audio duration without downloading the whole file immediately.

If you need several audio formats, extend the shortcode with more <source> elements. For a site that only publishes MP3 files, I would keep it this small.