diff --git a/js/actionTypes.js b/js/actionTypes.js index 780df0db..060b634b 100644 --- a/js/actionTypes.js +++ b/js/actionTypes.js @@ -65,3 +65,4 @@ export const MEDIA_TAG_REQUEST_FAILED = "MEDIA_TAG_REQUEST_FAILED"; export const NETWORK_CONNECTED = "NETWORK_CONNECTED"; export const NETWORK_DISCONNECTED = "NETWORK_DISCONNECTED"; export const UPDATE_WINDOW_POSITIONS = "UPDATE_WINDOW_POSITIONS"; +export const CHANNEL_COUNT_CHANGED = "CHANNEL_COUNT_CHANGED"; diff --git a/js/media/detectChannels.js b/js/media/detectChannels.js new file mode 100644 index 00000000..16a2b428 --- /dev/null +++ b/js/media/detectChannels.js @@ -0,0 +1,53 @@ +// Get the max value from an array-like +const max = arr => arr.reduce((acc, val) => Math.max(acc, val)); + +function createAnalysers(source) { + const { context } = source; + const splitter = context.createChannelSplitter(); + const leftGain = context.createGain(); + const rightGain = context.createGain(); + const leftAnalyser = context.createAnalyser(); + const rightAnalyser = context.createAnalyser(); + + source.connect(splitter); + splitter.connect(leftGain, 0); + splitter.connect(rightGain, 1); + leftGain.connect(leftAnalyser); + rightGain.connect(rightAnalyser); + + return { left: leftAnalyser, right: rightAnalyser }; +} + +const MAX_CALLS = 1000; + +export default async function detectChannels(source) { + return new Promise((resolve, reject) => { + const { left, right } = createAnalysers(source); + + const dataArray = new Uint8Array(left.frequencyBinCount); + let maxLeft = 0; + let maxRight = 0; + let calls = 0; + const intervalHandle = setInterval(() => { + left.getByteFrequencyData(dataArray); + maxLeft = Math.max(maxLeft, max(dataArray)); + right.getByteFrequencyData(dataArray); + maxRight = Math.max(maxRight, max(dataArray)); + + if (maxLeft > 0) { + if (maxRight > 0) { + resolve(2); + } else { + resolve(1); + } + clearInterval(intervalHandle); + } + + if (calls >= MAX_CALLS) { + reject(); + } + + calls++; + }, 20); + }); +} diff --git a/js/media/index.js b/js/media/index.js index 01d45e74..e0df181c 100644 --- a/js/media/index.js +++ b/js/media/index.js @@ -1,6 +1,7 @@ /* Emulate the native