Home > OS >  How can I play multiple audio sounds using JavaScript while using 1 class/1 ID and not having to use
How can I play multiple audio sounds using JavaScript while using 1 class/1 ID and not having to use

Time:01-28

I have multiple audio files (5). I'm attaching the files to an image so that when they are clicked, they play a specific audio. However, I have to use 5 different IDs & functions to make them play a unique sound.

HTML:

<img src="image1" alt=""  id="" value="PLAY" onclick="ricekrispy()">
        
<audio id="ricekrispy" src="sound.mp3"></audio>

<img src="image2" alt=""  id="" value="PLAY" onclick="skittles()">
        
<audio id="skittles" src="sound.mp3"></audio>

<img src="image3" alt=""  id="" value="PLAY" onclick="Mandms()">
        
<audio id="Mandms" src="audio3.mp3"></audio>

<img src="image4" alt=""  id="" value="PLAY" onclick="nuggets()">
        
<audio id="nuggets" src="audio4.mp3"></audio>

<img src="image5" alt=""  id="" value="PLAY" onclick="fries()">
        
<audio id="fries" src="audio5.mp3"></audio>

JavaScript:

function ricekrispy() {
    let audio = document.getElementById('ricekrispy');
    audio.play();
  }

  function skittles() {
    let audio = document.getElementById('skittles');
    audio.play();
  }

  function mandms() {
    let audio = document.getElementById('mandms');
    audio.play();
  }

  function nuggets() {
    let audio = document.getElementById('nuggets');
    audio.play();
  }

  function fries() {
    let audio = document.getElementById('fries');
    audio.play();
  }

I reused the functions and changed the name 1 by 1. I'm looking for a way to use a forEach to grab the element/ID/class without having to put script onto the element

(value="play" & onclick="function()")

CodePudding user response:

The OP might consider a more modern and generic DOM scripting approach which frees the OP from most id attributes and from inline-scripting.

The next following implementation uses ...

One would query a node-list of image elements which all feature a custom data-audio-source attribute.

document.querySelectorAll('img[data-audio-source]');

Such data-* global attributes are good for carrying additional information which relates to the very element that is featuring it. Here one would assign the audio-source that is related to its image.

<img src="/path/to/image" data-audio-source="/path/to/audio" />

One then needs to subscribe forEach node-list's image-element an event-listener with a callback-function which handles e.g. the image-element's 'click'-event.

The handler-function which gets passed as callback to addEventListener expects an event-object as its sole parameter. The event's currentTarget does refer to the clicked image-element (the very target of the event subscription). Since such an element features a custom data-audio-source attribute one can read the attribute-value via the element's related dataset-property ...

const source = elmImg.dataset.audioSource;

Within the handler one would query the correct audio-player element, pause it, assign the correct media-source/reference to it and start playing it (again).

function handleAutoPlay(evt) {
  const elmImg = evt.currentTarget;
  const source = elmImg.dataset.audioSource;

  const elmPlayer = document.querySelector('#auto-player');
  
  elmPlayer.pause();
  elmPlayer.src = source;
  elmPlayer.play();
}
document
  .querySelectorAll('img[data-audio-source]')
  .forEach(elmImg =>
    elmImg.addEventListener('click', handleAutoPlay)
  );
body { margin: 0; }
p { margin: 0 0 5px 0; }
img[data-audio-source] { height: 70px; cursor: pointer; }
<p>
  Featuring royalty-free sounds from
  <a href="https://soundbible.com/royalty-free-sounds-1.html">
    soundbible.comy
  </a>
  and free pictures from
  <a href="https://picsum.photos/images">
    Lorem Picsum
  </a>
</p>

<img
  src="https://fastly.picsum.photos/id/364/5000/2917.jpg?hmac=xXeSnI5JaHB8KssawSc9gjgKEorKVXx7T_YgPCf2F-A"
  data-audio-source="https://soundbible.com/mp3/airplane-landing_daniel_simion.mp3"
/>
<img
  src="https://fastly.picsum.photos/id/404/3264/2176.jpg?hmac=3lDeBx5WYEse6sijzGfqsQniZqTpFmfFlDnBC3cXzao"
  data-audio-source="https://soundbible.com/mp3/heavy-rain-daniel_simon.mp3"
/>
<img
  src="https://fastly.picsum.photos/id/111/367/267.jpg?hmac=4RBVF232Jl16jusqD0DurHz2lI4m6I8SVW7J6bSnK0Y"
  data-audio-source="https://soundbible.com/mp3/old-car-engine_daniel_simion.mp3"
/>
<img
  src="https://fastly.picsum.photos/id/419/3456/2304.jpg?hmac=RXPdqWRwlAeofpGH8aDVH7Yz7h2VklC82ppVCx5wnKk"
  data-audio-source="https://soundbible.com/mp3/service-bell_daniel_simion.mp3"
/>
        
<audio id="auto-player" controls></audio>

  • Related