AudioContext: phương thức createMediaElementSource()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2021.

Phương thức createMediaElementSource() của giao diện AudioContext được dùng để tạo một đối tượng MediaElementAudioSourceNode mới từ một phần tử HTML <audio> hoặc <video> hiện có; âm thanh từ phần tử đó sau đó có thể được phát và xử lý.

Để biết thêm chi tiết về các media element audio source node, hãy xem trang tham chiếu MediaElementAudioSourceNode.

Cú pháp

js
createMediaElementSource(myMediaElement)

Tham số

myMediaElement

Một đối tượng HTMLMediaElement mà bạn muốn đưa vào đồ thị xử lý âm thanh để thao tác.

Giá trị trả về

Một MediaElementAudioSourceNode.

Ví dụ

Ví dụ đơn giản này tạo một nguồn từ phần tử <audio> bằng createMediaElementSource(), sau đó đưa âm thanh qua một GainNode trước khi chuyển tới AudioDestinationNode để phát. Khi con trỏ chuột di chuyển, hàm updatePage() được gọi và tính gain hiện tại theo tỉ lệ giữa vị trí Y của chuột và chiều cao tổng thể của cửa sổ. Vì vậy, bạn có thể tăng hoặc giảm âm lượng nhạc đang phát bằng cách di chuyển con trỏ chuột lên xuống.

Note: Bạn cũng có thể xem ví dụ này chạy trực tiếp, hoặc xem mã nguồn.

js
const audioCtx = new AudioContext();
const myAudio = document.querySelector("audio");

// Create a MediaElementAudioSourceNode
// Feed the HTMLMediaElement into it
const source = audioCtx.createMediaElementSource(myAudio);

// Create a gain node
const gainNode = audioCtx.createGain();

// Create variables to store mouse pointer Y coordinate
// and HEIGHT of screen
let curY;
const HEIGHT = window.innerHeight;

// Get new mouse pointer coordinates when mouse is moved
// then set new gain value
document.onmousemove = updatePage;

function updatePage(e) {
  curY = e.pageY;
  gainNode.gain.value = curY / HEIGHT;
}

// Connect the AudioBufferSourceNode to the gainNode
// and the gainNode to the destination, so we can play the
// music and adjust the volume using the mouse cursor
source.connect(gainNode);
gainNode.connect(audioCtx.destination);

Note: Do hệ quả của việc gọi createMediaElementSource(), việc phát âm thanh từ HTMLMediaElement sẽ được định tuyến lại vào đồ thị xử lý của AudioContext. Vì vậy, bạn vẫn có thể phát/tạm dừng phương tiện thông qua API của phần tử phương tiện và các nút điều khiển trình phát.

Thông số kỹ thuật

Specification
Web Audio API
# dom-audiocontext-createmediaelementsource

Tương thích trình duyệt

Xem thêm