Contents

How to insert an audio player into a static Hugo-based site

Objective.

It may happen that you need to insert a static file audio player into a web page. In my case I needed it to publish sounds derived from the Apollo missions for home automation (I talk about it here). Even in the case of a Jamstack-based site like HUGO, it is possible with little to integrate the code needed to employ the native player within the html5 standard for audio and music playback.

Shortcode creation

Per farlo con la tecnologia HUGO basta avvalersi del componente shortcode. In pratica dobbiamo definire al nostro compilatore HUGO un template di html da impiegare e caricare a richiesta nei nostri file .md (ulteriori dettagli sulla Documentazione ufficiale).

Lo shortcode deve essere definito in layouts/shortcodes/audio.html. Questo รจ uno shortcode semplicissimo pensato per oggetti mp3, wav o ogg.

1
2
3
4
5
6
7
8
<div class="container">
<audio controls style="width: 100%; margin-bottom: 20px">
    {{ with .Get "wav" }}<source type="audio/wav" src="{{ . }}">{{ end }}
    {{ with .Get "ogg" }}<source type="audio/ogg" src="{{ . }}">{{ end }}
    {{ with .Get "mp3" }}<source type="audio/mpeg" src="{{ . }}">{{ end }}
    Your browser does not support the audio element.
{</audio>
</div>
Note
In this case I have set width and margin-bottom in a fixed way, nothing prohibits employing parameters for these values as well, for example with width="{{ .Get “width”}}"

The mp3 property in this case indicates the source of the file with that format and is passed as a parameter of the shortcode. For convenience we can add the file in the same folder as the .md file that will call it, this way we do not have to worry about relative paths.

Calling up the shortcode in the page.

To call up the test file “test.mp3” which is in the same folder as the article in markdown .md format we will just need to use the code:

1
{{< audio mp3=carengine.mp3 >}}

Demo

Here is the result:

Thanks to pixabay for providing the audio file.

Caution
Using this approach, the file will be easily downloadable to site visitors.

Compatibility.

According to the Mozilla documentation, compatibility on modern browsers is guaranteed.

Minimum versions of compatible browsers.

Minimum versions of compatible browsers.

Extra - View shortcode as source code.

In writing this article, I ran into a problem with displaying the shortcode code within the article itself. Inserting the string {{< shortcode >}} in the text or in a source code box of a Hugo page will not have the desired outcome, as the site’s compiler will replace the code with the relevant declared template. To show the code as is and inhibit the substitution you will need to insert characters to comment out the shortcode like this:

1
{{</* audio mp3="audio file" */>}}