Skip to content

Commit

Permalink
Merge pull request #90 from HamStudy/feature/TypedArraySupport
Browse files Browse the repository at this point in the history
Feature/typed array support
  • Loading branch information
edimuj authored Jun 5, 2019
2 parents 79ac7db + e7b9703 commit 90e9034
Showing 1 changed file with 39 additions and 6 deletions.
45 changes: 39 additions & 6 deletions www/audioInputCapture.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ var exec = require('cordova/exec');

var audioinput = {};

var hasTypedArrays = 'Int16Array' in window && 'Float32Array' in window;

// Audio formats
audioinput.FORMAT = {
PCM_16BIT: 'PCM_16BIT',
Expand Down Expand Up @@ -364,13 +366,29 @@ audioinput._audioInputDebugEvent = function (debugMessage) {
};

/**
* Normalize audio input
*
* @param {Object} pcmData
* @private
* Returns a typed array, normalizing if needed
* @param {number[]} pcmData - Array of short integers which came from the plugin
*/
audioinput._normalizeAudio = function (pcmData) {
function normalizeToTyped(pcmData) {
if (audioinput._cfg.normalize) {
var out = Float32Array.from(pcmData, function(i) {
return parseFloat(i) / audioinput._cfg.normalizationFactor;
});
// If last value is NaN, remove it.
if (isNaN(out.subarray[out.length - 1])) {
return out.subarray(0, out.length - 1);
}
return out;
}

return Int16Array.from(pcmData);
}

/**
* Returns a standard javascript array, normalizing if needed
* @param {number[]} pcmData - Array of short integers which came from the plugin
*/
function normalizeNoTyped (pcmData) {
if (audioinput._cfg.normalize) {
for (var i = 0; i < pcmData.length; i++) {
pcmData[i] = parseFloat(pcmData[i]) / audioinput._cfg.normalizationFactor;
Expand All @@ -383,7 +401,22 @@ audioinput._normalizeAudio = function (pcmData) {
}

return pcmData;
};
}

/**
* Normalize audio input
*
* If typed arrays are supported by the browser then a Float32Array will be returned
* if nomalization is enabled; if not then a Int16Array will be returned. These are
* much more efficient to work with since you can get subarrays without copying them.
* If typed arrays are not supported then a normal array will be returned
*
* @param {Object} pcmData
* @private
*
* @returns {Int16Array|Float32Array|Array}
*/
audioinput._normalizeAudio = hasTypedArrays ? normalizeToTyped : normalizeNoTyped;


/**
Expand Down

0 comments on commit 90e9034

Please sign in to comment.