November 22, 2022
Let's start out by importing an audio file. This isn't a native Webflow feature, so let's upload our file to any kind of cloud storage (Dropbox, Google Drive).
Now we need to get an URL to the source of the audio file. If you're unsure about how to get this, simply Google how to get it from your selected cloud storage service.
Now drag in an Embed element and create an audio HTML5 element like so:
<audio src="https://youraudiosource.com" class="audio"></audio>
Make sure to use your own URL in the src.
We'll give it a class or something like audio. Make sure to remember the class for the next step.
Let's create a native Webflow button and give it a class of play or something similar.
Now we need to reference the audio element in our Javascript. Here we'll store it inside a variable called audio. We'll add all our Javascript (and/or jQuery) code in between script tags before our closing body tag in the page settings.
const audio = document.querySelector("audio");
In order to toggle the audio, we need to keep track of if the audio file is currently playing or not. We do this by creating a new variable and setting it to false as default.
let isPlaying = false;
Now let's use jQuery's click method on our play button. Here we'll check if the audio is currently playing. If it is, we'll set the isPlaying variable to false while also pausing the audio. If it's not playing we'll set it to true and play the audio.
$(document).ready(function () {
$(".play").click(function () {
if (isPlaying) {
audio.pause();
isPlaying = false;
} else {
audio.play();
isPlaying = true;
}
});
});
We can further develop this by setting the text of our button to Play or Pause depending on what the audio's currently doing. It could look something like this:
$(document).ready(function () {
$(".play").click(function () {
if (isPlaying) {
audio.pause();
isPlaying = false;
// Setting the button text
$(this).html("Play");
} else {
audio.play();
isPlaying = true;
// Setting the button text
$(this).html("Pause");
}
});
});
And there we have it. If you need more help in figuring out how this works, feel free to watch this video which explains it in detail. Have fun.