当前位置: 动力学知识库 > 问答 > 编程问答 >

How to get sound from java-based services

问题描述:

I have a Java-based server side and a flex client side using Spring BlazeDS Integration. It works fine, but I want to get sound from server side recently.

I followed this BlazeDS mapping doc, it says when Java return a Byte[], it will be converted to ByteArray which I want. So I handle the MP3 file by ByteArrayOutputStream, convert it to Byte[] and return it back to front-end, but the value that Actionscript gets turns to be null value.

public Byte[] sayHello() {

Byte[] ba = null;

try {

FileInputStream fis = new FileInputStream(

"D:/e/Ryan Adams - I Wish You Were Here.mp3");

ByteArrayOutputStream baos = new ByteArrayOutputStream();

byte[] buffer = new byte[8192];

int bytesRead;

while ((bytesRead = fis.read(buffer)) > 0) {

baos.write(buffer, 0, bytesRead);

}

byte[] byteArray = baos.toByteArray();

ba = new Byte[byteArray.length];

for (int i = 0; i < byteArray.length; i++) {

ba[i] = Byte.valueOf(byteArray[i]);

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return ba;

}

The ActionScript code:

<s:RemoteObject id="ro" destination="helloWorldService" fault="handleFault(event)">

<s:channelSet>

<s:ChannelSet>

<s:AMFChannel uri="/flexspring/messagebroker/amf"/>

</s:ChannelSet>

</s:channelSet>

</s:RemoteObject>

...

private function loaded():void {

var bArr:ByteArray = ro.sayHello() as ByteArray;

l.text = "" + (bArr == null);

}

...

<s:Label id="l" text=""/>

And it says "true". Does anyone have any idea what's the problem.

网友答案:

The problem with your code is that all flex calls over a BlazeDS are async. So, ro.SomeMethod() doesn't return immediately, it queues it up and then does callbacks as necessary.

Here's an example of something that works Note that I've never sent byte[] over a BlazeDS connection, but I don't see why it wouldn't work --- as J_A_X suggests, you probably want to stream the sound, rather than sending the whole thing at once.

Anyway - here's the example:

public function loaded():void
{
   var token:AsyncToken = ro.sayHello();
   token.addResponder(new mx.rpc.Responder(result, fault));
   // ...Code continues to execute...
}

public function result(event:ResultEvent):void
{
   // The byte[] is in event.result
   var bArr:ByteArray = event.result as ByteArray;
}

public function fault(event:FaultEvent):void 
{
   // Something went wrong (maybe the server on the other side went AWOL) 
}
网友答案:

You can return the sound bytes through a web service. After you got the bytes, you can add it to a Sound object and play that. The only problem is that since it's a web service, the client will have to load all the bytes before it can play. If you want to stream the sound, you'll need a streaming server like FMS or Wowza (I recommend the latter).

分享给朋友:
您可能感兴趣的文章:
随机阅读: