8.3.Mp3文件的播放和暂停

8.3.1. 问题
我希望允许用户播放一系列的MP3 文件。
8.3.2. 解决办法
使用Sound 和SoundChannel 类,当用户选择一个新的MP3 类时,使用渐进式下载方式下在一个新的文件。
8.3.3. 讨论
Sound 类的play 方法返回一个SoundChannel 对象,它提供存取的方法和属性控制左右声道声音音量的平衡,还有暂停和恢复一个特定声音的方法。

例子,你可以使用这样的代码来装载和播放声音文件:
+展开
-ActionScript
var snd:Sound = new Sound(new URLRequest("sound.mp3"));
var channel:SoundChannel = snd.play();

你不能用ActionScript 代码暂停一个声音的播放,你只能使用SoundChannel 的stop 方法停止播放。不过,您可以从任何一个时间点开始播放声音。也可以纪录声音停止的时间点,并且从这个时间点开始播放后面的声音。

当声音播放时,SoundChannel.position 属性指示声音文件现在播放的位置。当声音播放停止是纪录时间点的值:
+展开
-ActionScript
var pausePosition:int = channel.position;
channel.stop();

需要恢复声音时,传递前面纪录的时间点值,声音会从前面停止时的位置重新开始播放:
+展开
-ActionScript
channel = snd.play(pausePosition);

下面的完整代码提供了一个组合框允许用户选择不同的MP3 文件,暂停和停止播放使用了SoundChannel 类:
+展开
-XML
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxmlwidth="400height="300">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
public var sound:Sound;
public var chan:SoundChannel;
public var pausePos:int = 0;
private const server:String = "http://localhost:3001/"
private var dp:ArrayCollection =
new ArrayCollection(["Plans.mp3""Knife.mp3",
"Marla.mp3""On a Neck, On a Spit.mp3",
"Colorado.mp3"])
private function loadSound():void {
if(chan != null) {
//make sure we stop the sound; otherwise, they'll overlap
chan.stop();
}
//re-create sound object, flushing the buffer, and readd the
event listener
sound = new Sound();
sound.addEventListener(Event.SOUND_COMPLETE,
soundComplete);
var req:URLRequest = new URLRequest(server +
cb.selectedItem as String);
sound.load(req);
pausePos = 0;
chan = sound.play();
}p
private function soundComplete(event:Event):void {
cb.selectedIndex++;
sound.load(new URLRequest(server +
cb.selectedItem as String));
chan = sound.play();
}
private function playPauseHandler():void
{
if(pausePlayBtn.selected){
pausePos = chan.position;
chan.stop();
else {
chan = sound.play(pausePos);
}
}

]]>
</mx:Script>
<mx:ComboBox creationComplete="cb.dataProvider=dpid="cb"
change="loadSound()"/>

<mx:Button label="startid="pausePlayBtntoggle="true"
click="playPauseHandler()"/>

<mx:Button label="stopclick="chan.stop()"/>
</mx:HBox>

加支付宝好友偷能量挖...


评论(0)网络
阅读(103)喜欢(0)flash/flex/fcs/AIR