AudioWorkletGlobalScope: thuộc tính sampleRate

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.

Thuộc tính chỉ đọc sampleRate của giao diện AudioWorkletGlobalScope trả về một số thực float biểu thị tốc độ lấy mẫu của BaseAudioContext liên kết mà worklet thuộc về.

Giá trị

Một số dấu phẩy động biểu thị tốc độ lấy mẫu liên kết.

Ví dụ

AudioWorkletProcessor có thể truy cập các thuộc tính riêng của AudioWorkletGlobalScope:

js
// AudioWorkletProcessor defined in : test-processor.js
class TestProcessor extends AudioWorkletProcessor {
  constructor() {
    super();

    // Logs the current sample-frame and time at the moment of instantiation.
    // They are accessible from the AudioWorkletGlobalScope.
    console.log(currentFrame);
    console.log(currentTime);
  }

  // The process method is required - output silence,
  // which the outputs are already filled with.
  process(inputs, outputs, parameters) {
    return true;
  }
}

// Logs the sample rate, that is not going to change ever,
// because it's a read-only property of a BaseAudioContext
// and is set only during its instantiation.
console.log(sampleRate);

// You can declare any variables and use them in your processors
// for example it may be an ArrayBuffer with a wavetable.
const usefulVariable = 42;
console.log(usefulVariable);

registerProcessor("test-processor", TestProcessor);

Kịch bản chính tải processor, tạo một thể hiện của AudioWorkletNode, truyền tên của processor cho nó và kết nối node đó vào một đồ thị âm thanh. Chúng ta sẽ thấy đầu ra của các lệnh gọi console.log() trong console:

js
const audioContext = new AudioContext();
await audioContext.audioWorklet.addModule("test-processor.js");
const testNode = new AudioWorkletNode(audioContext, "test-processor");
testNode.connect(audioContext.destination);

Thông số kỹ thuật

Specification
Web Audio API
# dom-audioworkletglobalscope-samplerate

Khả năng tương thích với trình duyệt

Xem thêm