Skip to content

Commit

Permalink
Improve audio interleaving (#100)
Browse files Browse the repository at this point in the history
* Improve _interleave performance

* Fix indentation
  • Loading branch information
yudori authored Dec 18, 2023
1 parent 6d63dd5 commit 5c1ab66
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/crunker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -394,17 +394,24 @@ export default class Crunker {
* @internal
*/
private _interleave(input: AudioBuffer): Float32Array {
const channels = Array.from({ length: input.numberOfChannels }, (_, i) => i);
const length = channels.reduce((prev, channelIdx) => prev + input.getChannelData(channelIdx).length, 0);
if (input.numberOfChannels === 1) {
// No need to interleave channels, just return single channel data to save performance and memory
return input.getChannelData(0);
}
const channels = [];
for (let i = 0; i < input.numberOfChannels; i++) {
channels.push(input.getChannelData(i));
}
const length = channels.reduce((prev, channelData) => prev + channelData.length, 0);
const result = new Float32Array(length);

let index = 0;
let inputIndex = 0;

// for 2 channels its like: [L[0], R[0], L[1], R[1], ... , L[n], R[n]]
while (index < length) {
channels.forEach((channelIdx) => {
result[index++] = input.getChannelData(channelIdx)[inputIndex];
channels.forEach((channelData) => {
result[index++] = channelData[inputIndex];
});

inputIndex++;
Expand Down

0 comments on commit 5c1ab66

Please sign in to comment.