Embed audio files using native tags

A question in the textpattern forum prompted a more general interest in short-tags, Textpattern’s addition to its arsenal available from version 4.7.+. The idea of short-tags is explained in the docs but it is basically an adoption of much of the functionalities of smd_macro, which allowed for plugin-like calls from articles. To understand shor-tags a knowledge of the updated yield and variable tags is recommended.

This tip will hopefully shed some light on its basic usage. The code creates a container for audio-files which can then be embedded in the articles.

First create a miscellaneous form and call it audio and paste the following code.

<audio controls>
<txp:variable name="audio_file" value='<txp:yield name="title" />' />
	<txp:if_variable name="audio_file">
		<txp:if_yield name="m4a">
			<source src="/files/<txp:variable name="audio_file" />.m4a" type="audio/m4a">
		<txp:if_yield name="mp3">
			<source src="/files/<txp:variable name="audio_file" />.mp3" type="audio/mpeg">
		<txp:if_yield name="ogg">
			<source src="/files/<txp:variable name="audio_file" />.ogg" type="audio/ogg">
Your browser does not support the audio element.

How it works

The new html 5 audio tag, provides native playback of audio files in most modern browsers. This of course also depends on what audio extensions your computer supports. The audio tag is allowing for an automatic choice by the computer of which file to play.

The above code, which assumes that the same file name will be used for different encodings of the same audio file, can be called in an article by very simply using <txp::audio title="your_title" m4a mp3 />.

A breakdown of this tag is self evident once the logic is understood. ie. The code will load the m4a and mp3 versions uploaded by the wbmaster in the files directory whilst the yield tag is used to define the audio file’s name.

The final parsed html will look like:

<audio controls>
	<source src="/files/your_title.m4a" type="audio/m4a">
	<source src="/files/your_title.mp3" type="audio/mpeg">

Happy listening!

comments powered by Disqus