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


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

p5.j​​s庫的p5.MediaElement的addCue()方法用於安排某個事件,隻要媒體元素到達指定的提示點,便觸發該事件。它接受一個回調函數,該函數可用於指定事件期間應執行的操作。也可以使用此方法將可選參數傳遞給回調函數。

用法:

addCue( time, callback, value)

參數:該函數接受上麵提到和下麵描述的三個參數。

  • time:它是一個數字,指定相對於媒體元素的時間(以秒為單位),在該時間之後將調用給定的回調函數。
  • callback:這是在給定時間調用的函數。
  • value:這是一個作為參數傳遞給回調函數的對象。它是一個可選參數。

返回值:此方法返回一個數字,該數字表示添加的提示的“id”。這可用於以後訪問或刪除提示。

範例1:以下示例說明了p5.js庫的addCue()方法。



Javascript

function setup() { 
  createCanvas(550, 400); 
  textSize(18); 
  
  text("The events in addCue() are called " + 
       "according to the given time", 20, 20); 
  
  example_media = 
    createVideo("sample-video.mp4"); 
  example_media.size(426, 240); 
  example_media.position(20, 60); 
  example_media.showControls(); 
  
  // Using the addCue() method for specifying 
  // the time that the callback function 
  // would be called 
  example_media.addCue(3, showTime, 
                       example_media); 
  example_media.addCue(5, showTime, 
                       example_media); 
  example_media.addCue(8, showTime, 
                       example_media); 
  example_media.addCue(10, showTime, 
                       example_media); 
} 
  
function showTime(media) { 
  
  // Set a random background color 
  r = random(255); 
  g = random(255); 
  b = random(255); 
  background(r, g, b); 
  
  // Get the media element from the callback 
  let mediaTime = media.time(); 
  
  text("The current time of the video is:" + 
       mediaTime, 20, 340); 
  
    text("The events in addCue() are called " + 
       "according to the given time", 20, 20); 
}

輸出:

範例2:

Javascript

let y = 0; 
  
function setup() { 
  createCanvas(550, 400); 
  textSize(18); 
  
  text("The addCue() function is called " + 
       "according to the given time", 20, 20); 
  
  example_media = 
    createVideo("sample-video.mp4"); 
  example_media.size(426, 240); 
  example_media.position(20, 60); 
  example_media.showControls(); 
  
  // Using the addCue() method for specifying 
  // the time that the callback function 
  // would be called 
  example_media.addCue(3, changePlaySpeed, 
                       0.15); 
  example_media.addCue(5, changePlaySpeed, 
                       1.0); 
  example_media.addCue(8, changePlaySpeed, 
                       3.0); 
} 
  
function changePlaySpeed(amount) { 
  
  // Get the amount from the callback 
  example_media.speed(amount); 
  
  text("The current speed of the video is:"
       + amount, 20, y + 340); 
  
  y += 20; 
}

輸出:

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

相關用法


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