Created
June 17, 2012 18:15
-
-
Save manuelnelson/2945258 to your computer and use it in GitHub Desktop.
Modifying and Sending Raw Binary Data in Javascript Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$('#saveSample').click(function () { | |
$('#loading').show(); | |
try { | |
var buffer = getFinalSampleBuffer(); | |
} | |
catch (ex) { | |
Mashup.ShowMessage(ex); | |
return false; | |
} | |
var request = new XMLHttpRequest(); | |
request.open("post", "/postUrlHere/", true); | |
request.onreadystatechange = function () { | |
if (request.readyState == 4 && request.status == 200) { | |
callback(request.responseText); | |
} else if (request.readyState == 4 && request.status != 200) { | |
Mashup.ShowMessage("No Way Jose", "There was a problem saving the sample"); | |
} | |
}; | |
// Send the file | |
request.send(buffer); | |
}); | |
//For this gist this function is cut and paste from a larger jquery widget I created, hence the this' that | |
//don't quite make sense. I try to explain the properties as I go | |
function getFinalSampleBuffer() { | |
var startByte = this.playWaveformStart * 4; //start of user selected sample in bytes | |
var endByte = this.playWaveformEnd * 4; //end of user selected sample in bytes | |
//http://stackoverflow.com/questions/6170421/blobbuilder-ruins-binary-data | |
var uint8Array = new Uint8Array(this.buffer.getChannelData(0).buffer); //Grabs the Float32Array buffer | |
var byteLength = endByte - startByte; | |
var sampleByteArray = new Uint8Array(byteLength); | |
for(var i = startByte; i<endByte;i++) { | |
sampleByteArray[i-startByte] = uint8Array[i]; | |
} | |
var BlobBuilderObj = new (window.BlobBuilder || window.WebKitBlobBuilder)(); | |
BlobBuilderObj.append(sampleByteArray.buffer); | |
var blob = BlobBuilderObj.getBlob('text/plain'); | |
return blob; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment