Flash - passing audio data ByteArray to javascript

2019-07-25 12:31发布

问题:

I'm able to record sound with a Flash application embedded in my website, this audio is saved to a ByteArray, which I need to pass to Javascript in order to post to my server along with other required data.

I know I can use AS3 ExternalInterface class to communicate with Flash from Javascript, but what would be the appropriate format or variable type in javascript to hold the ByteArray, and how can I ensure that I won't lose much audio data when doing so?

回答1:

Maybe it's not possible for you for some reason I'm not aware of, but if that's not the case, I'd post the data directly from Actionscript (you can send binary data).

Anyway, if you have to relay the data to JS, the safest way would be base64-encoding the ByteArray. After that you have a string that will not have any control (read: problematic) characters.

Size is of course something to take into account. I don't know what are the limitations of ExternalInterface (I've only ever used it to pass small ammounts of data), but you'll most likely hit a hard limit there. LocalConnection objects have a limit of 100 kb or so if I recall correctly (these are not related to the ExternalInterface api -at least not directly- but I mention it just as a remainder of the possible limitations). If you're working with raw audio, your data will be rather big, so you'd have to figure out how to compress it (and decompress it in the JS end or in the server) and also, probably, how to send it in chunks, as sending it all at once will likely be impossible if the data is too big.

Again, if possible, I'd post directly from Actionscript and would use at least the ByteArray's compress method before sending the data.



回答2:

This code worked for me (rec is ByteArray):

    rec.position = 0;
    rec.compress();
    var b64:Base64Encoder = new Base64Encoder();
    b64.encodeBytes(rec);
    ExternalInterface.call('soundRecorded', b64.toString());

It sucessfully handles about 6 megabytes of data (I didn't try more).