音楽をスクリプトで再生する

説明

HTML 5で音楽をスクリプトで再生するにはaudioタグに対してplay()メソッドを使います。play()は最初から再生するのではなく、再生ポインタがある位置から再生を行います。

サンプルプログラム

【HTML】
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>Sample</title>
<link rel="stylesheet" href="css/main.css" type="text/css" media="all">
<script type="text/javascript" src="js/sample.js"></script>
</head>
<body>
<h1>サウンドを再生する</h1>
<div id="contents">
<audio id="myAudio" controls style="width:400px;">
<source src="music/hydrancer.ogg">
<source src="music/hydrancer.mp4">
<source src="music/hydrancer.mp3">
<p>audioタグに対応したブラウザでお聴き下さい</p>
</audio>
<button onclick="playAudio()">再生する</button>
</div>
</body>
</html>


【sample.js】
function playAudio(){
document.getElementById("myAudio").play();
}
サンプルを実行
[戻る]