1. 程式人生 > >用javascript呼叫聲音檔案或者視訊檔案

用javascript呼叫聲音檔案或者視訊檔案

在主頁中編制音訊播放器
    雖然NetscapeNavigator3.0和InternetExplorer都支援音訊檔案的播放,但在製作過程中還是遇到了這樣一個問題: 如果用隱藏方式播放則沒有音效卡的使用者要出錯,而且因為是後臺播放使用者無法控制其暫停、播放和停止;如果不隱藏,因為播放器是黑色背景無論放在哪兒都覺得彆扭,影響主頁的效果。而自編一個既便於使用者控制又能給頁面起到點綴作用的音訊播放器不失為一個好辦法。下面詳細介紹用JavaScript 自編音訊播放器的方法。

     1. NetscapeNavigator3.0的音訊播放器

    1).直接開啟

    NetscapeNavigator3.0支援.mid、 .wav和.au等音訊檔案格式,您可以在瀏覽器中直接開啟上述檔案,開啟時出現如下圖的播放器視窗並自動播放一次,繼續播放可單擊“PLAY”按鈕。



    2).程式呼叫

    在主頁檔案中您可以嵌入如下名為MySound的音訊控制檯來實現隱藏方式下音訊 檔案的自動迴圈播放:
  < EMBED
  SRC="jn.mid"//原始檔名
  HIDDEN="TRUE"//隱藏方式
  AUTOSTART="TRUE"//自動播放
  LOOP="TRUE"//迴圈播放
  NAME="MySound"//嵌入物件名
  < /EMBED>

     2. JavaScript的音訊支援函式
  通過JavaScript的音訊支援函式您可以控制任何一個嵌入在主頁中的音訊控制檯。 JavaScript提供瞭如下的支援函式:
  play({loop[TRUE,FALSEoranINT]},′{url-to-sound}′)//播放

  pause()//暫停
  stop()//停止播放當前檔案
  StopAll()//停止播放所有檔案
  start-time({numberofseconds})//從第幾秒開始
  end-time({numberofseconds})//到第幾秒結束
  setvol({percentagenumber-without"%"sign})//音量百分比控制
  fade-to({volumepercentyouwishtofadeto-withoutthe"%"sign})//削減音量到
  fade-from-to({volumepercentstartfade},{volumepercentendfade})//從某個音量值削減到某個音量值

  start-at-beginning()//從檔案頭開始
  stop-at-end()//到檔案尾停止
  下面四個是狀態測試函式
  IsReady()//準備狀態測試
  IsPlaying()//播放狀態測試
  IsPaused()//暫停狀態測試
  GetVolume()//獲取當前音量值

     3. 應用舉例

    下面是一個包含NetscapeNavigator3.0音訊播放器所有五個元素的例子。考慮到有些使用者沒有音效卡,本例中沒有設定自動播放。讀者可以根據自己的喜好結合滑鼠事件將各個元素和測試函式都新增到圖形按鈕中。程式清單如下:
  < HTML>
  < HEAD>
  < TITLE>自編音訊播放器演示< /TITLE>
  < SCRIPTLANGUAGE=JavaScript>
  < !--Writer:YuHaiHe
  functionplaySound(){
  document.firstSound.play(true);
  }
  functionpauseSound(){
  document.firstSound.pause();
  }
  functionstopSound(){
  document.firstSound.stop();
  }
  functionvolup(){
  currentVolume=document.firstSound.GetVolume();
  newVolume=(currentVolume+10);
  if(document.firstSound.GetVolume()==100){
  alert("音量已經達到最大值");
  }
  if(newVolume<101){
  document.firstSound.setvol(newVolume);
  }
  else
  {
  if((newVolume<=100)&&(newVolume>90)){
  document.firstSound.setvol(100);
  }
  }
  }
  functionvoldown(){
  currentVolume=document.firstSound.GetVolume();
  newvolume=(currentVolume-10);
  if(document.firstSound.GetVolume()==0){
  alert("音量已經達到最小值");
  }
  if(newVolume>0){
  document.firstSound.setvol(newVolume);
  }
  else
  {
  if((newVolume>=0)&&(newVolume<10)){
  document.firstSound.setvol(0);
  }
  }
  }
  //EndofJavaScriptCode-->
  < /SCRIPT>
  < /HEAD>
  < BODY>
  < EMBED
  SRC="JN.MID"
  HIDDEN=TRUE
  AUTOSTART="FALSE"
  LOOP="TRUE"
  NAME="firstSound"
  MASTERSOUND>
  < P>< AHREF="">播放< /A>< /P>
  < P>< AHREF="">暫停< /A>< /P>
  < P>< AHREF="">停止< /A>< /P>
  < P>< AHREF="">音量+< /A>< /P>
  < P>< AHREF="">音量-< /A>< /P>
  < /BODY>
  < /HTML>