1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| // ------------------------
// 1- définition des touches et des fichiers musiques associées
var keyboard = [
{ 'charCode':113,'keyName':'Q','music':'https://www.memoclic.com/medias/sons-wav/2/729.wav'},
{ 'charCode':115,'keyName':'S','music':'https://www.memoclic.com/medias/sons-wav/2/728.wav'},
{ 'charCode':100,'keyName':'D','music':'https://www.memoclic.com/medias/sons-wav/2/727.wav'},
{ 'charCode':102,'keyName':'F','music':'https://www.memoclic.com/medias/sons-wav/2/726.wav'},
{ 'charCode':103,'keyName':'G','music':'https://www.memoclic.com/medias/sons-wav/2/725.mp3'},
{ 'charCode':104,'keyName':'H','music':'https://www.memoclic.com/medias/sons-wav/2/724.mp3'},
{ 'charCode':106,'keyName':'J','music':'https://www.memoclic.com/medias/sons-wav/2/723.mp3'},
{ 'charCode':107,'keyName':'K','music':'https://www.memoclic.com/medias/sons-wav/2/722.mp3'},
];
// console.log( keyboard );
// ------------------------
// 2- construction du code HTML des TOUCHES
var div_audio_keyboard = document.getElementById('audio-keyboard');
keyboard.forEach( function(key){
// audio-keyboard
var div_touche = document.createElement('div');
div_touche.className = 'touche';
div_touche.setAttribute('id','touche-'+key.charCode);
div_touche.setAttribute('data-key',key.charCode);
div_touche.setAttribute('data-music',key.music);
div_touche.textContent = key.keyName;
div_audio_keyboard.appendChild(div_touche);
// de la forme : <div class="touche" id="touche-113" data-key="113" data-music="xxxxxxxxxx.mp3">Q</div>
});
// ------------------------
// 3- click sur une TOUCHE (ECRAN)
var touches = document.querySelectorAll('.touche');
touches.forEach( function(touche){
touche.addEventListener('click',function(){
// console.log('play : '+touche.dataset.key );
playSound(touche);
});
});
// ------------------------
// 4- click au CLAVIER
document.addEventListener('keypress', function(event){
// console.log(event);
var touche = document.getElementById('touche-'+event.charCode);
if( touche ) { playSound(touche); }
});
// ------------------------
// 5- play
function playSound(touche){
// touche
touche.style.backgroundColor = "grey";
setTimeout(function(){ touche.style.backgroundColor = ""; }, 200);
// player audio
var audio = new Audio(touche.dataset.music);
audio.play();
}
// ------------------------ |