views:

2859

answers:

4

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). I have to play it, but I can not, what shall I do?


I tried the next code to play that buffrer(ByteArray\Stream) (I get MP3 data from server the method of getting data works fine (tested on text int's etc) I call the returned ByteArray readResponse because I have some seading method and It is it's response).

      protected function Play(event:MouseEvent):void
  {
   var mySound:Sound = new Sound();
   mySound.addEventListener(SampleDataEvent.SAMPLE_DATA, soundFill);
   mySound.play(); 
  }

  public function soundFill(event:SampleDataEvent):void
  {
   event.data.writeBytes(readResponse.buffer, 0, readResponse.buffer.length); 
  }
+1  A: 

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.

Joshua Noble
A: 

Hi Joshua and everybody. I am trying to run your code, but I am getting a severely distorted, unrecognized sound. this returns with mp3 or wav (PCM) on any sampling rates. anyone else had this problem ? thanks

A: 

Hi I have the same issue

Saswaan
+2  A: 

This one doesn't work since SampleDataEvent.data expects uncompressed raw sample data, not MP3. Use http://wiki.github.com/claus/as3swf/play-mp3-directly-from-bytearray instead.

Shimray