How to play MP3 sound from buffer (ByteArray/Stream) in ActionScript 3?

后端 未结 3 2072
庸人自扰
庸人自扰 2021-02-05 18:19

So.. I have a buffer with MP3 data (If I would save this buffer and call it buffer.mp3 it would play, but in this situation I should not save it to file system)

3条回答
  •  终归单人心
    2021-02-05 19:09

    The following works for me:

    package
    {
     import flash.display.Sprite;
     import flash.events.Event;
     import flash.events.SampleDataEvent;
     import flash.media.Sound;
     import flash.media.SoundChannel;
     import flash.net.URLRequest;
     import flash.net.URLStream;
     import flash.utils.ByteArray;
    
     public class QuickSoundTest extends Sprite
     {
      public var sampleMP3:Sound;
      private var soundChannel:SoundChannel; 
      public var bArr:ByteArray;
    
      public function QuickSoundTest()
      {
       sampleMP3 = new Sound();
    
       var urlReq:URLRequest = new URLRequest("test.mp3");
       var urlStream:URLStream = new URLStream();
       urlStream.addEventListener(Event.COMPLETE, loaded);
       urlStream.load(urlReq);
    
      }
    
      private function loaded(event:Event):void {
       var urlStream:URLStream = event.target as URLStream;
       bArr = new ByteArray();
       urlStream.readBytes(bArr, 0, 40960);
       sampleMP3.addEventListener(SampleDataEvent.SAMPLE_DATA, sampleDataHandler);
       soundChannel = sampleMP3.play();
      }
    
      private function sampleDataHandler(event:SampleDataEvent):void {
       event.data.writeBytes(bArr, 0, 40960);
      }
     }
    }
    

    You might need to check what is stored in your readResponse ByteArray or how the data is getting read in when you're loading it. Making sure that it's loaded the URLLoader using URLLoaderDataFormat.BINARY or just by using a URLStream as I've done here.

提交回复
热议问题