【AS3代码】MP3音乐的播放/暂停/设定音量大小
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundTransform;
import flash.net.URLRequest;
public class Main extends Sprite
{
private var _sound:Sound;
private var _channel:SoundChannel;
private var _playing:Boolean = false;
private var _playPauseButton:Sprite;
private var _position:int;
private var _trans:SoundTransform
public function Main():void
{
_sound = new Sound(new URLRequest("music.mp3"));
_channel = _sound.play();
_trans = new SoundTransform();
_trans.volume = 0.3; //音量大小设置(0关闭,1最大)
_channel.soundTransform = _trans; //绑定音量设置
//正在播放状态
_playing = true;
//生成一个播放(暂停)按钮
_playPauseButton = new Sprite();
addChild(_playPauseButton);
_playPauseButton.graphics.beginFill(0xff0000);
_playPauseButton.graphics.drawRect(50,50,60,40);
_playPauseButton.graphics.endFill()
_playPauseButton.addEventListener(MouseEvent.MOUSE_UP, onPlayPause);
}
private function onPlayPause(evt:MouseEvent):void
{
//如果正在播放,此次单击则为暂停
if(_playing)
{
_position = _channel.position; //将暂停的当前处保存起来
_channel.stop(); //暂停
}
else
{
_channel = _sound.play(_position); //从暂停处继续播放
}
trace("当前播放长度:" + Math.round(_channel.position) + " / 总长:" + Math.round(_sound.length));
_playing = !_playing; //两种状态转换(播放中/暂停中)
}
}
}
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundTransform;
import flash.net.URLRequest;
public class Main extends Sprite
{
private var _sound:Sound;
private var _channel:SoundChannel;
private var _playing:Boolean = false;
private var _playPauseButton:Sprite;
private var _position:int;
private var _trans:SoundTransform
public function Main():void
{
_sound = new Sound(new URLRequest("music.mp3"));
_channel = _sound.play();
_trans = new SoundTransform();
_trans.volume = 0.3; //音量大小设置(0关闭,1最大)
_channel.soundTransform = _trans; //绑定音量设置
//正在播放状态
_playing = true;
//生成一个播放(暂停)按钮
_playPauseButton = new Sprite();
addChild(_playPauseButton);
_playPauseButton.graphics.beginFill(0xff0000);
_playPauseButton.graphics.drawRect(50,50,60,40);
_playPauseButton.graphics.endFill()
_playPauseButton.addEventListener(MouseEvent.MOUSE_UP, onPlayPause);
}
private function onPlayPause(evt:MouseEvent):void
{
//如果正在播放,此次单击则为暂停
if(_playing)
{
_position = _channel.position; //将暂停的当前处保存起来
_channel.stop(); //暂停
}
else
{
_channel = _sound.play(_position); //从暂停处继续播放
}
trace("当前播放长度:" + Math.round(_channel.position) + " / 总长:" + Math.round(_sound.length));
_playing = !_playing; //两种状态转换(播放中/暂停中)
}
}
}