您的位置:首页 > 产品设计 > UI/UE

使用URLRequest获取MP3并进行播放的例子

2011-03-31 10:14 549 查看
通过URL地址获取一个MP3并进行播放的例子

首先使用URLRequest获取MP3 然后使用sound对象load方法读取 最后使用soundChannel对象进行播放
将这个方法编写成一个类 代码如下

 

package
{
public class AlarmSound
{

import flash.events.*;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.net.URLRequest;

import mx.events.FlexEvent;

public var soundChannel:SoundChannel = new SoundChannel();
public var playing:Boolean=false;
public var soundUrl:String="";

public function AlarmSound()
{

}

public function soundPlay():void
{
trace("playing:"+playing);
if(!playing)
{
var sound:Sound = new Sound();
var mp3URL:URLRequest=new URLRequest(soundUrl);
sound.addEventListener(Event.COMPLETE,soundStart);
sound.load(mp3URL);
trace(soundUrl);
}
}

public function soundStop():void
{
if(playing)
{
soundChannel.stop();
soundChannel.removeEventListener(Event.SOUND_COMPLETE,soundEnd);
playing = false;
}
}

private function soundStart(event:Event):void
{
if(!playing)
{
var sound:Sound = event.target as Sound;
soundChannel = sound.play();
soundChannel.addEventListener(Event.SOUND_COMPLETE,soundEnd);
playing = true;

sound.removeEventListener(Event.COMPLETE,soundStart);
sound = null;

}
}

private function soundEnd(event:Event):void
{
trace("播放完毕");
playing = false;

}

}
}


 

这个类有两个对外的方法 一个是 soundPlay 另外一个是soundStop

 

使用方法如下

var s1:AlarmSound = new AlarmSound();
s1.soundUrl = "http://www.cy1001.net/goodtime.mp3";
s1.soundPlay();

//停止
s1.soundStop();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息