0

I need help looping a HTML5 audio clip.

I have the below script, but it only plays once. I need it to play the music clip when the link is pressed and plays non-stop in a loop. The audio can only then be stopped when refreshing the page or but selecting the link again:

<a href="#music" onclick="clicksound.playclip()" style="cursor: default;">Link here</a>

<script>
// Sound for background music
var html5_audiotypes={
"mp3": "audio/mpeg",
"mp4": "audio/mp4",
"ogg": "audio/ogg",
"wav": "audio/wav"
}

function createsoundbite(sound){
var html5audio=document.createElement('audio')
if (html5audio.canPlayType){ //check support for HTML5 audio
for (var i=0; i<arguments.length; i++){
var sourceel=document.createElement('source')
sourceel.setAttribute('src', arguments[i])
if (arguments[i].match(/\.(\w+)$/i))
sourceel.setAttribute('type', html5_audiotypes[RegExp.$1])
html5audio.appendChild(sourceel)
}
html5audio.load()
html5audio.playclip=function(){
html5audio.pause()
html5audio.currentTime=0
html5audio.play()
}
return html5audio
}
else{
return {playclip:function(){throw new Error("")}}
}
}

//Initialize two sound clips with 1 fallback file each:

var mouseoversound=createsoundbite("music.ogg", "music.mp3")
var clicksound=createsoundbite("music.ogg", "music.mp3")
</script>

Thank you.

Timothy
  • 1
  • 2

1 Answers1

2

why don't you try using the audio tag and add the attribute loop so it would loop back to back

replace the src with your own audio file to see it looping

<h1>The audio loop attribute</h1>

<p>Click on the play button to play a sound:</p>

<audio controls loop>
  <source src="https://www.w3schools.com/tags/horse.ogg" type="audio/ogg">
  <source src="https://www.w3schools.com/tags/horse.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>

click this link to see its working

  • Thank you, I will check it out. I was after the link to be played on an image, so if you click on the image the audio clip would play. – Timothy Aug 12 '21 at 13:20