當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


p5.js MediaElement volume()用法及代碼示例

p5.j​​s中p5.MediaElement的volume()方法用於設置或返回媒體元素的當前音量。可以使用介於0.0和1.0之間的值來指定體積,其中0.0表示介質中沒有體積,而值1.0表示最大體積。任何中間值均可用於指定所需的體積。

可以通過不向該函數傳遞任何參數來返回當前的介質體積。

用法:

volume( val )

參數:此方法接受如上所述和以下描述的單個參數:

  • val:該數字指定要設置的音量。體積可以在0.0到1.0之間。它是一個可選參數。

返回值:此方法返回一個Number,表示媒體元素的當前體積。



以下示例說明了p5.js中的volume()方法:

範例1:

Javascript

let currVolume = 0.5; 
  
function setup() { 
    createCanvas(500, 400); 
    textSize(18); 
  
    text("Click on the buttons to increase " + 
         "or decrease the volume", 20, 20); 
  
    example_media = 
      createVideo("sample-video.mp4"); 
    example_media.size(500, 300); 
    example_media.position(20, 100); 
    example_media.showControls(); 
  
    example_media.volume(currVolume); 
  
    incBtn = createButton("Increase Volume"); 
    incBtn.position(30, 40); 
    incBtn.mousePressed(incVol); 
  
    decBtn = createButton("Decrease Volume"); 
    decBtn.position(160, 40); 
    decBtn.mousePressed(decVol); 
  
    text("The video is playing at " + 
         "half volume", 20, 80); 
} 
  
function incVol() { 
  clear(); 
  
  if (currVolume < 0.9) 
    currVolume += 0.1; 
  
  // Set the new higher volume 
  example_media.volume(currVolume); 
  
  text("The volume has been increased", 
       20, 80); 
  
  text("Click on the buttons to increase " +  
       "or decrease the volume", 20, 20); 
} 
  
function decVol() { 
  clear(); 
  
  if (currVolume > 0.1) 
    currVolume -= 0.1; 
  
  // Set the new lower volume 
  example_media.volume(currVolume); 
  
  text("The volume has been decreased", 
       20, 80); 
  
  text("Click on the buttons to increase " + 
       "or decrease the volume", 20, 20); 
}

輸出:

範例2:

Javascript

function setup() { 
  createCanvas(500, 400); 
  textSize(20); 
  
  text("Move the slider to increase or " + 
       "decrease the volume", 20, 20); 
  
  example_media = 
    createVideo("sample-video.mp4"); 
  example_media.size(500, 300); 
  example_media.position(20, 80); 
  
  example_media.showControls(); 
  
  volSlider = 
    createSlider(0.0, 1.0, 0.5, 0.1); 
  volSlider.position(20, 40); 
  volSlider.input(changeVol); 
} 
  
function changeVol() { 
  clear(); 
  
  let volumeVal = volSlider.value(); 
  
  // Set the media volume to the slider value 
  example_media.volume(volumeVal); 
  
  // Get the current volume 
  let currVolume = example_media.volume(); 
  
  text("Move the slider to increase or " + 
       "decrease the volume", 20, 20); 
  text("Video is playing at volume:" + 
       currVolume, 20, 80); 
}

輸出:

在線編輯: https://editor.p5js.org/
環境設置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
參考: https://p5js.org/reference/#/p5.MediaElement/volume

相關用法


注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 p5.MediaElement volume() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。