2010-08-04 196 views
2

無論我做什麼,我都無法在Firefox或IE或Chrome中播放聲音。使用JavaScript播放聲音

<html> 
<head> 
<script type="text/javascript"> 

    function play() 
{ 
    var embed = document.createElement('object'); 

    embed.setAttribute('src', 'c:\\test.wav'); 
    embed.setAttribute('hidden', true); 
    embed.setAttribute('autostart', true); 
    embed.setAttribute('enablejavascript', true); 

    document.childNodes[0].appendChild(embed); 

} 

// --> 
</script> 
</head> 
<body onload="play();"> 
</body> 
</html> 
+14

**請不要**有背景音樂播放當頁面加載時自動。這是一個網頁最煩人的事情之一(見http://www.seomoz.org/blog/how-to-convince-a-client-their-site-doesnt-need-music)。至少可以選擇將其靜音。 – 2010-08-04 05:33:31

+2

你的問題之一是'\ t'是選項卡。 – 2010-08-04 05:33:40

+0

修正了\ t的事情,但仍然沒有運氣。 – FaNIX 2010-08-04 05:39:35

回答

6

嘗試使用的功能發揮()

function play() 
{ 
    var embed=document.createElement('object'); 
    embed.setAttribute('type','audio/wav'); 
    embed.setAttribute('data', 'c:\test.wav'); 
    embed.setAttribute('autostart', true); 
    document.getElementsByTagName('body')[0].appendChild(embed); 
} 

與您的代碼的問題是你使用src屬性,這對於<嵌入>標籤這個修訂版本。而是使用<對象>標記的數據屬性。



如果您試圖從中獲得最大的兼容性,您還應該考慮添加嵌入標記作爲對象標記的替代方法。它的工作方式是這樣的:

<object data="test.wav" type="audio/wav" autostart="true"> 
<embed src="test.wav" autostart="true" alt="Could not load audio" /> 
</object> 

的使用方法類似noscript標記,在舊的瀏覽器不支持object標籤訴諸嵌入標籤。

+0

不,這似乎也沒有播放文件.... – FaNIX 2010-08-04 05:49:39

+0

你確定你有一個有效的WAV文件?我在發佈之前在計算機上測試了我的代碼,並且它在Google Chrome上完美運行。嘗試將test.wav文件放在與html文件相同的目錄中,並將data屬性設置爲'test.wav'。另外,你能否讓我知道你正在使用哪個瀏覽器,這樣我可以檢查自己? – Kranu 2010-08-04 06:16:02

+0

好吧,我將文件移至相同的文件夾,它使用谷歌瀏覽器,但不與Firefox。我其實只需要它在Firefox中工作。 – FaNIX 2010-08-04 06:19:18

0

使用<embed>標籤的FYI將使您的代碼無效。目前你有兩種選擇,如果你想播放你的網頁上的聲音:[1]使用這種方法,它適用於大多數瀏覽器,但會使HTML失效(使用<embed>)或[2]使用只能在某些最新瀏覽器中使用的方法,但是這將是未來的方式,也被認爲是有效的HTML(使用<audio><object>)。

2

試試這個方法,在所有的瀏覽器來播放聲音:

function playSound(soundfile_ogg, soundfile_mp, soundfile_ma) { 
    if ("Audio" in window) { 
     var a = new Audio(); 
     if (!!(a.canPlayType && a.canPlayType('audio/ogg; codecs="vorbis"') 
       .replace(/no/, ''))) 
      a.src = soundfile_ogg; 
     else if (!!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, 
       ''))) 
      a.src = soundfile_mp; 
     else if (!!(a.canPlayType && a.canPlayType(
       'audio/mp4; codecs="mp4a.40.2"').replace(/no/, ''))) 
      a.src = soundfile_ma; 
     else 
      a.src = soundfile_mp; 

     a.autoplay = true; 
     return; 
    } else { 
     alert("Time almost up"); 
    } 
} 

播放聲音,做這樣的事情:

playSound("/file/horse.wav", "/file/horse.mp3","/file/horse.m4a");