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.
|
|
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:
|
|
Demo
Here is the result:
Compatibility.
According to the Mozilla documentation, compatibility on modern browsers is guaranteed.
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:
|
|