Web Play Sound-flash (play AMR, WAV)

Source: Internet
Author: User

This article mainly introduces the Flash play AMR format Base64 code audio.

Before this has been contacted Flash, contact AS3 is confused, but fortunately there is TypeScript and JavaScript Foundation does not seem very laborious, now learn to sell is to open a "jumping pit" trip ~ ~ ~

1. Realization of Ideas

At first a little realization of ideas are wood, do not know where to start, only know to use Flash to play AMR, degree Niang goojje a meal to find, the results can be imagined, no bad, only very bad, haha.

Later thought, all things have to have a train of thought, can not be done, suddenly suddenly dawned, for their own waste of a day's time, feel ashamed and afraid ....

What audio ①flash can play.

② how AMR is converted into Flash playable audio in ActionScript.

How to invoke methods in ActionScript in ③js, and how to interact.

④ How to embed a SWF file in an HTML page.

⑤ How to encapsulate Amr (Audio) and Flash play Amr two ways.

2. Break each of them individually

What audio ①flash can play:

MP3 format is the default supported by the Flash audio format, WAVE format needs to be converted to play, other formats need to be converted, because the first to do the Chrome play a sound, some understanding of the wave audio, so decided to start from the wave audio, so according to the above-mentioned routines to "thinking “:

(1) Regardless of how the conversion, it is sure to manipulate the byte array, so the first step to the AMR format Base64 code into the ByteArray array.

(2) How to convert AMR ByteArray into WAVE format ByteArray array, there is no doubt that the process must be decoded.

In accordance with these two small steps, and quickly found the Base64 transcoding process (began to use as to achieve the JS in the transcoding process, usable but not perfect, the final reference on GitHub on the conversion process of Daniel),

But AMR conversion WAVE This is not so easy, finally determined that as the AMR more laborious, need to use C language to decode, and then use Crossbirdge to generate a SWC file that can be called by Flash.

OK, so far, the first step is the perfect solution.

② how AMR is converted into Flash playable audio in ActionScript:

As mentioned above, we need to use C language for AMR decoding, the following will give the C language decoding and generation of SWC tutorial (for reference Daniel).

How to invoke the method in ActionScript, how to interact, the complete code is posted in the following (be sure to look at comments, comments, comments ), and write the JS call procedure here.

JS Code:

functionCallflashmethod () {//Play is a externalinterface.addcallback ("Play", this.play) defined in the Flash code and is described in more detail below. Thismovie ("<object> ID on embedded page"). Play ("Base64str");}functionThismovie (moviename) {if(Navigator.appName.indexOf ("Microsoft")! =-1) {        returnWindow[moviename]}Else {        returnDocument[moviename]}} document.getElementById ("Playid"). onclick =function() {Callflashmethod ();};

④ How to embed a SWF file in an HTML page:

Use Swfobject.js to embed a SWF file in an HTML page, reference: http://www.cnblogs.com/Carpe-Diem/articles/2310831.html

⑤ How to encapsulate Amr (Audio) and Flash play Amr two ways:

With the above cushion, it is easy to encapsulate (mainly see Isie as true):

  

varRongimlib; (function(rongimlib) {varRongimvoice = (function () {        functionRongimvoice () {}/** * Initialize sound library*/Rongimvoice.init=function () {            if( This. Isie) {                vardiv = document.createelement ("div"); Div.setattribute ("id", "flashcontent");                Document.body.appendChild (DIV); varScript = document.createelement ("Script"); SCRIPT.SRC= "Http://cdn.ronghub.com/swfobject-2.0.0.min.js"; varHeader = document.getElementsByTagName ("head") [0];                Header.appendchild (script); SetTimeout (function () {                    varSwfversionstr = "11.4.0"; varFlashvars = {}; varparams = {}; Params.quality= "High"; Params.bgcolor= "#ffffff"; Params.allowscriptaccess= "Always"; Params.allowfullscreen= "true"; varattributes = {}; Attributes.id= "Player"; Attributes.name= "Player"; Attributes.align= "Middle"; swfobject.embedSWF ("Http://cdn.ronghub.com/player-2.0.2.swf", "Flashcontent", "1", "1", Swfversionstr,NULL, flashvars, params, attributes); }, 200); }            Else {                varList = ["Http://cdn.ronghub.com/pcmdata-2.0.0.min.js", "Http://cdn.ronghub.com/libamr-2.0.1.min.js"];  for(vari = 0, len = list.length; i < Len; i++) {                    varScript = document.createelement ("Script"); SCRIPT.SRC=List[i];                Document.head.appendChild (script); }            }             This. Isinit =true;        }; /** * start playing sound * @param data {string} AMR format Base64 code * @param duration {Number} plays approximately data.lengt h/1024*/Rongimvoice.play=function(data, duration) { This. Checkinit ("Play"); varme = This; if(Me.isie) {Me.thismovie (). DoAction ("Init", data); }            Else{me.palyvoice (data);            me.oncompleted (duration);        }        }; /** * Stop playing sound*/Rongimvoice.stop=function () {             This. Checkinit ("Stop"); varme = This; if(Me.isie) {Me.thismovie (). DoAction ("Stop"); }            Else {                if(me.element) {me.element.stop ();        }            }        }; /** * method to call when playing sound*/rongimvoice.onprogress=function () {             This. Checkinit ("OnProgress");        }; Rongimvoice.checkinit=function(postion) {if(! This. Isinit) {                Throw NewError ("Rongimvoice not initialized,postion:" +postion);        }        }; Rongimvoice.thismovie=function () {            returnEval ("window[' Player ')");        }; Rongimvoice.oncompleted=function(duration) {varme = This; varCount = 0; varTimer = SetInterval (function() {count++;                Me.onprogress (); if(Count >=duration)                {clearinterval (timer); }            }, 1000); if(Me.isie) {Me.thismovie (). DoAction ("Play");        }        }; Rongimvoice.base64toblob=function(Base64data, type) {varMimeType; if(type) {MimeType={Type:type}; } base64data= Base64data.replace (/^ (. *) [,]/, '); varSlicesize = 1024; varBytecharacters =Atob (Base64data); varByteslength =bytecharacters.length; varSlicescount = Math.ceil (Byteslength/slicesize); varBytearrays =NewArray (Slicescount);  for(varSliceindex = 0; Sliceindex < Slicescount; ++Sliceindex) {                varBegin = Sliceindex *slicesize; varend = Math.min (begin +slicesize, byteslength); varbytes =NewArray (End-begin);  for(varoffset = begin, i = 0; Offset < end; ++i, + +offset) {Bytes[i]= Bytecharacters[offset].charcodeat (0); } Bytearrays[sliceindex]=NewUint8array (bytes); }            return NewBlob (Bytearrays, MimeType);        }; Rongimvoice.palyvoice=function(base64data) {varReader =NewFileReader (), blob = This. Base64toblob (Base64data, "Audio/amr"), ME = This; Reader.onload=function () {                varSamples =NewAMR ({benchmark:true}). Decode (Reader.result); Me.element=AMR.util.play (samples);            };        Reader.readasbinarystring (BLOB);        }; Rongimvoice.isie=/trident/. Test (navigator.useragent); Rongimvoice.isinit=false; returnRongimvoice;    })(); Rongimlib.rongimvoice=Rongimvoice; //compatible with AMD CMD    if("function" = = =typeofRequire && "object" = = =typeofModule && module && module.id && "object" = = = =typeofExports &&exports) {Module.exports=Rongimvoice; }    Else if("function" = = =typeofDefine &&define.amd) {define ("Rongimvoice", [],function () {            returnRongimvoice;    }); }}) (Rongimlib|| (Rongimlib = {}));

As of Here, Flash play AMR format base64 code is finished, mainly talk about ideas, think the demo address, you can again "Web play sound-Introduction article" Download.

Web Play Sound-flash (play AMR, WAV)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.