HTML5新機能 〜 audio要素

HTML5の新機能の1つ「audio要素」を試してみた。


http://wbs-newworld.appspot.com/html5study.html

実際に、検証アプリを作成した。

しかし、ハマった><。currrentTimeへの値の設定が、期待通りに動作せず、困った。document.getElementById("id").currentTime = 0と書いても、0がセットされないのだ。

原因は、スクリプトタグの位置だった。ケアレスミスDOMがロードされてから実行しなければならないので、最後に書く必要があった。DOMContentLoadイベントのハンドラで行っても良いのかもしれない。

■HTMLソースコード

<!DOCTYPE html>
<html lang="ja">
<head>
<!--[if lt IE 9]>
<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<meta charset="utf-8"/>
<title>タイトル</title>
<link rel="stylesheet"  href="sample.css"/>

<!-- ここに記述しては動かない 
<script src="javascript/audio.js"></script>
-->
<style>
h1 {color:red}
</style>
</head>
<body>
<!-- コンテンツ部分 -->
<!-- audio要素 -->
<audio id="audio" controls>
<source src="media/workaholic.mp3" type="audio/mp3"></source>
<p>ブラウザがaudio要素に対応していません</p>
</audio><br>
<input type="button" value="再生" onclick="audioPlay()"/>
<input type="button" value="一時停止" onclick="audioMomentaryPause()"/>
<input type="button" value="停止" onclick="audioPause()"/>
<input type="button" value="早送り" onclick="audioFastForward()"/>
<input type="button" value="巻き戻し" onclick="audioFastRewind()"/>

<!-- DOMが読み込まれてからJSを読み込む -->
<script src="javascript/audio.js"></script>
</body>
</html>

上のHTMLでインポートしているaudio.jsは下記である。

	var audioId = 'audio';
	var audioObject = document.getElementById(audioId);

	//再生
	function audioPlay(){
		document.getElementById(audioId).play();
	};

	//一時停止
	function audioMomentaryPause(){
		document.getElementById(audioId).pause();
	};

	//停止
	function audioPause(){
		document.getElementById(audioId).pause();
		document.getElementById(audioId).currentTime = 0;
	};

	//早送り
	function audioFastForward(){
		document.getElementById(audioId).playbackRate += 0.5;
	};

	//巻き戻し
	function audioFastRewind(){
		document.getElementById(audioId).currentTime -= 0.5;
	};