前回の質問と回答してくださった方の意見リンク内容をふまえ、
リンク内容
こちらのサイトを参考にaudioタグとjQueryを使って試しにつくってみたのですが、
音をならすことができませんでした。
コードは以下のようになります
html
1<!DOCTYPE html> 2<html> 3 4<title>ホームページ</title> 5 6<head> 7 8 9<!--jQuery本体--> 10<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 11 12<!--自分で作るjQueryプログラム--> 13<script src="sample.js"></script> 14 15</head> 16<body background="img/nm001.png"> 17 18 19 20 21<!--ボタン--> 22<button type="button"><a class="sounds" data-file="morning">morning</a></button> 23 24</body> 25</html>
jQuery
1 2$(document).ready(function() { 3 //対応拡張子をチェック 4 var audio = new Audio(); 5 if(audio.canPlayType('audio/mp3')){ 6 var a_type = '.mp3'; 7 } else if(audio.canPlayType('audio/wav')){ 8 var a_type = '.wav'; 9 } 10 //audioタグを作る 11 $('.sounds').each(function(){ 12 var file = $(this).attr('data-file'); 13 $('body').append('<audio id="'+file+'" preload="auto"></audio>'); 14 $('#'+file).attr('src', './sound/'+file+a_type); 15 }); 16 クリックされた要素と同じaudioを再生する 17 $('.sounds').bind('click'function() { 18 var file = $(this).attr('data-file'); 19 $('audio').each(function(){ 20 $(this).get(0).pause(); 21 $(this).get(0).currentTime = 0; 22 }); 23 $('#'+file).get(0).play(); 24 }); 25});
参考にしたサイトから変更した点はjQueryのtouchstartをclickに、htmlの画像クリックの部分をボタンにしました。
コードに間違いがあるのでしょうか
フォルダの構造は下のような感じで
soundフォルダの中にmorning.mp3とmorning.wavが入っています