BaseAudioContext: phương thức createGain()
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 createGain() của giao diện BaseAudioContext
tạo một GainNode, có thể được dùng để điều khiển gain tổng thể (hay âm lượng) của đồ thị âm thanh.
Note:
Hàm dựng GainNode()
là cách được khuyến nghị để tạo một GainNode; xem
Tạo một AudioNode.
Cú pháp
createGain()
Tham số
Không có.
Giá trị trả về
Một GainNode nhận một hoặc nhiều nguồn âm thanh làm đầu vào và xuất ra âm thanh đã được điều chỉnh gain (âm lượng) tới mức được chỉ định bởi tham số a-rate GainNode.gain của node.
Ví dụ
Ví dụ sau cho thấy cách dùng cơ bản một AudioContext để tạo một GainNode, sau đó dùng node này để tắt tiếng và bật lại tiếng khi nhấp vào nút Mute bằng cách thay đổi giá trị thuộc tính gain.
Đoạn mã dưới đây sẽ không chạy nguyên trạng. Để xem ví dụ hoạt động đầy đủ, hãy xem bản demo Voice-change-O-matic của chúng tôi (xem mã nguồn.)
<div>
<button class="mute">Mute button</button>
</div>
const audioCtx = new AudioContext();
const gainNode = audioCtx.createGain();
const mute = document.querySelector(".mute");
let source;
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia(
// constraints - chỉ cần âm thanh cho ứng dụng này
{
audio: true,
},
// Callback thành công
(stream) => {
source = audioCtx.createMediaStreamSource(stream);
},
// Callback lỗi
(err) => {
console.error(`The following gUM error occurred: ${err}`);
},
);
} else {
console.error("getUserMedia not supported on your browser!");
}
source.connect(gainNode);
gainNode.connect(audioCtx.destination);
// …
mute.onclick = () => {
if (mute.id === "") {
// 0 nghĩa là tắt tiếng. Nếu bạn vẫn nghe thấy âm thanh, hãy chắc chắn
// rằng bạn chưa kết nối nguồn vào đầu ra ngoài việc dùng GainNode.
gainNode.gain.setValueAtTime(0, audioCtx.currentTime);
mute.id = "activated";
mute.textContent = "Unmute";
} else {
gainNode.gain.setValueAtTime(1, audioCtx.currentTime);
mute.id = "";
mute.textContent = "Mute";
}
};
Thông số kỹ thuật
| Specification |
|---|
| Web Audio API> # dom-baseaudiocontext-creategain> |