MCPcopy Create free account
hub / github.com/Vanilagy/webcodecs-polyfill / constructor

Method constructor

src/audio_data.ts:71–123  ·  view source on GitHub ↗
(init: AudioDataInit | Frame)

Source from the content-addressed store, hash-verified

69 constructor(init: Frame);
70 constructor(init: AudioDataInit);
71 constructor(init: AudioDataInit | Frame) {
72 if (init instanceof Frame) {
73 const format = toAudioSampleFormat(init.format as AVSampleFormat);
74 if (!format) {
75 throw new TypeError('Unsupported audio sample format: ' + init.format);
76 }
77
78 this.format = format;
79 this.sampleRate = init.sampleRate;
80 this.numberOfFrames = init.nbSamples;
81 this.numberOfChannels = init.channels;
82 this.timestamp = Number(init.pts);
83 this.duration = Number(init.duration);
84
85 this._data = init;
86 } else {
87 if (!Number.isFinite(init.sampleRate) || init.sampleRate <= 0) {
88 throw new TypeError('Invalid AudioDataInit: sampleRate must be > 0.');
89 }
90 if (!Number.isInteger(init.numberOfChannels) || init.numberOfChannels <= 0) {
91 throw new TypeError('Invalid AudioDataInit: numberOfChannels must be an integer > 0.');
92 }
93 // Spec: numberOfFrames is required and must be > 0
94 if (!Number.isInteger(init.numberOfFrames) || init.numberOfFrames <= 0) {
95 throw new TypeError('Invalid AudioDataInit: numberOfFrames must be an integer > 0.');
96 }
97 if (!Number.isFinite(init?.timestamp)) {
98 throw new TypeError('init.timestamp must be a number.');
99 }
100
101 this.format = init.format;
102 this.sampleRate = init.sampleRate;
103 this.numberOfFrames = init.numberOfFrames;
104 this.numberOfChannels = init.numberOfChannels;
105 this.timestamp = Math.trunc(init.timestamp);
106 this.duration = Math.floor(1e6 * this.numberOfFrames / init.sampleRate);
107
108 const dataBuffer = toUint8Array(init.data);
109
110 // Spec: Verify data has enough data.
111 const expectedSize
112 = this.numberOfFrames * this.numberOfChannels * getBytesPerSample(this.format);
113
114 if (dataBuffer.byteLength < expectedSize) {
115 throw new TypeError('Invalid AudioDataInit: insufficient data size.');
116 }
117
118 this._data = dataBuffer as Uint8Array<ArrayBuffer>;
119 }
120
121 finalizationRegistry.register(this, this._data instanceof Frame ? this._data : null, this);
122 openAudioDataCount++;
123 }
124
125 private ensureNotClosed() {
126 if (this.closed) {

Callers

nothing calls this directly

Calls 3

toAudioSampleFormatFunction · 0.85
toUint8ArrayFunction · 0.85
getBytesPerSampleFunction · 0.85

Tested by

no test coverage detected