DevonAero
DevonAero

Reputation: 75

How to play a certain audio file based on an user's click?

I'm building a "piano-like" music app, where users can click on a certain div (boxes) and it plays a note.

I know I could do this by grabbing all the Ids of both the boxes and the audio file, but I think there's an easier and more flexible way.

I tried looping through the boxes and grabbing the Ids, but I can't seem to get the names of audio files. I had an idea that I could get the Ids and see if they match the value of the name attribute for the audio and play it that way, but I'm stuck.

Here's the sample code:

<div id="main">
        <div id="box1" class="box"></div>
        <div id="box2" class="box"></div>
        <div id="box3" class="box"></div>
        <div id="box4" class="box"></div>
        <div id="box5" class="box"></div>
        <div id="box6" class="box"></div>
        <div id="box7" class="box"></div>
    </div>

<audio id="box1_sound" name="notes">
        <source src="audio/d_note.mp3" type="audio/mp3"></source>
    </audio>

JavaScript:

var box1 = document.getElementById('box1');
var box1Note = document.getElementById('box1_sound');

box1.addEventListener('mousedown', function(){
    box1Note.currentTime = 0;
    box1Note.play();
}); 

var boxName = document.getElementsByClassName('box');
var notes = document.getElementsByName('notes');

for (var j = 0; j < notes.length; j++) {
    var notesVal = notes[j].name;
    console.log(notesVal);
}

for (var i = 0; i < boxName.length; i++) {
    boxName[i].addEventListener('mousedown', function(){
        var boxId = this.id;
        console.log(boxId);

    });
}

Any help would be awesome, thanks guys!

Upvotes: 1

Views: 85

Answers (2)

Kenny Johnson
Kenny Johnson

Reputation: 784

What about putting an onclick handler on each div? Something like this:

<span onclick="playMusic('a.mp3')" class="white">  </span>
<span onclick="playMusic('b.mp3')" class="black">  </span>
<span onclick="playMusic('c.mp3')" class="white">  </span>
<span onclick="playMusic('d.mp3')" class="black">  </span>
<span onclick="playMusic('e.mp3')" class="white">  </span>
<span onclick="playMusic('d.mp3')" class="black">  </span>

Then just have some javascript that plays the specified audio file in that function? Here's a jsfiddle that shows my example in action.

Upvotes: 1

qtgye
qtgye

Reputation: 3610

You can try this work around:

Loop through each box. for each loop, grab the id of the box and concatenate to form the id name of the audio element.

example:

var boxes = document.querySelectorAll('.box');

for ( var i=0 ; i < boxes.length; i++) {   
    boxes[i].addEventListener('click',function(){
        sound = document.getElementById(this.id+'_sound');    
        sound.currentTime = 0;
        sound.play();
    });    
}

FIDDLE DEMO

Upvotes: 1

Related Questions