DIV CSS 佈局教程網

用 JavaScript 在網頁播放聲音,相容各種瀏覽器
編輯:關於JavaScript     

想在網頁上觸發播放一段音效,可以借助 SWFObject 嵌入一個 Flash 播放器,再由 JavaScript 呼叫它來播放指定的 mp3。以下是完整示例:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>SwfObject2.2Demo</title>
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
var flashvars = {
};
var params = {
wmode: "transparent"
};
var attributes = {};
swfobject.embedSWF("sound.swf", "sound", "1", "1", "9.0.0", "expressInstall.swf", flashvars, params, attributes);

function play(c) {
var sound = swfobject.getObjectById("sound");
if (sound) {
sound.SetVariable("f", c);
sound.GotoFrame(1);
}
}
</script>
</head>
<body>
<div id="sound">
</div>
<input type="button" value="播放" onclick="play('msg.mp3')" />
</body>
</html>

使用時,需要一併引入 swfobject.js 與 sound.swf(放在 js 特效資料夾裡)。點擊按鈕時,play() 會把要播放的 mp3 檔名寫入 Flash 變數並重新播放。同樣地,由於 Flash 已被淘汰,現今更推薦使用 HTML5 的 <audio> 標籤搭配 audio.play() 來實作網頁播放音效。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved