Bryan
Bryan

Reputation: 1

Play a sound when text is clicked

I am trying to write a page where when you click on a specific text, it plays a specific mp3 file (e.g. click on Text 1, it plays Sound 1, click on Text 2, it plays Sound 2...etc.). After a bit of research I found following code, but realized it won't work as intended if the code is replicated more than once. All text will only play the same 1st mp3 file in the entry.

 <audio id="audio" src="mp3 file 1" autostart="false" ></audio>
 <a onclick="playSound();"> Text 1</a>

 <audio id="audio" src="mp3 file 2" autostart="false" ></audio>
 <a onclick="playSound();"> Text 2</a>

 <audio id="audio" src="mp3 file 2" autostart="false" ></audio>
 <a onclick="playSound();"> Text 3</a>

Upvotes: 0

Views: 3697

Answers (3)

Gustav G
Gustav G

Reputation: 479

The easiest way I can think about is by using SoundPlayer.js.

Load it into your html:

<script type="text/javascript" src="https://gustavgenberg.github.io/handy-front-end/SoundPlayer.js"></script>

Add data attributes to your links containing the audio file source:

<a href="#" data-audio-src="file1.mp3">Text 1</a>
<a href="#" data-audio-src="file2.mp3">Text 2</a>
<a href="#" data-audio-src="file3.mp3">Text 3</a>

And use a loop to bind click events aswell as preloading the sound (1):

(1)

const player = new SoundPlayer();

const elements = document.querySelectorAll('[data-audio-src]');

for(let element of elements) {

  const audioSrc = element.getAttribute('data-audio-src');

  player.load(audioSrc);

  element.onclick = function () {

    player.get(audioSrc).play();

  }

}

// OR 

(2)

const player = new SoundPlayer();

const elements = document.querySelectorAll('[data-audio-src]');

for(let element of elements) {

  const audioSrc = element.getAttribute('data-audio-src');

  element.onclick = function () {

    player.load(audioSrc).play();

  }

}

Upvotes: 0

Jarlik Stepsto
Jarlik Stepsto

Reputation: 1725

You could add a data-audio-url attribute to your spans with text:

<span data-audio-url="mp3_file_1.mp3">Text1</span>
<span data-audio-url="mp3_file_2.mp3">Text2</span>
<span data-audio-url="mp3_file_3.mp3">Text3</span>

And add a init function to initialize your sound playing. By adding an onclick to each span, with data-audio-url

(i am using jquery, but it is also possible with pure javascript)

function initSounds() {

$("[data-audio-url]").each(
    function(){
        $(this).on('click', function() {
            var mp3Url = $(this).attr('data-audio-url');
            var a = new Audio(mp3Url);
            a.play();
        });
    }
);

}

What is this code doing:

To identify objects, that will play audio on click, we add an attribute to them (data-audio-url="xxx").
In our javascript we search for all the elements having this attribute $("[data-audio-url]")
Then we add an onclick event to each found element, you cand do this directly with the .on('click', function) or like me an an for each loop.
In the onclick i read the url $(this).attr('data-audio-url'); and then just create a new audio object with this url var a = new Audio(mp3Url);

Here is a simple fiddle, if you want to stop the last sound, you have to add some extra code.

Refferences:

  1. Audio API
  2. JQuery
  3. HTML data-* attribute
  4. JQuery Attribute Selector
  5. JQuery.each()
  6. JQuery.on()
  7. JQuery.attr()

EDIT:
You have to put the code in a onload function (like in the fiddle) or you copy the initSounds() function in your js file and call the function in an onload function.

EIDT2:
If you want to do it with your function, you could change the head of your playSound() function to something like this: function playSound(elementId){ ...

And then inside the function replace audio (the id) by elementId In your html you have to change the IDs of your audio elements in somethig unique and the onclick="playSound()" by onclick="playSound(audioElementId)" where audioElementId is the id of desired audio element.

Upvotes: 2

rainbowcat
rainbowcat

Reputation: 491

First, change the id values in each <audio> tag to be unique (e.g. id="audio1", id="audio2", id="audio3").

Then write your JavaScript to reference those tags by id and call play(). For example, document.getElementById('audio1').play(), plays the file specified by <audio id="audio1" ...>.

Upvotes: 0

Related Questions