我需要一个接一个地播放三个音乐曲目。有必要再次加载它并且在缓存中。 我用这个代码。在localhost上一切正常,但只有在服务器上重启应用程序后才能正常工作。每次重新下载曲目都是错误的。
public function musicOn():void{
if (sndStart == 'true'){
req = new URLRequest("media/" + track + ".mp3");
snd.load(req);
channel = snd.play();
channel.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete);
sndStart = 'false';
} else {
sndStart = 'true';
}
}
public function musicOff():void{
if (snd.length>0){
channel.stop();
snd = new Sound();
channel = new SoundChannel();
sndStart = 'true';
}
}
public function onPlaybackComplete(event:Event):void{
if (track==3){
track = 1;
} else {
track++;
}
sndStart = 'true';
snd = new Sound();
musicOn();
}
我运行这些功能:
if (optObj.music == 'true' && sndStart == 'true'){
musicOn();
} else if (optObj.music == 'false'){
musicOff();
}
optObj.music
- 当应用程序启动或调用函数时,调用参数的对象会更改设置。
答案 0 :(得分:5)
我不确定我理解你写的所有内容,但是这个怎么样:
package test
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.net.URLRequest;
public class SoundTest extends MovieClip
{
private var files : Array = [ "file1.mp3", "file2.mp3", "file3.mp3" ];
private var sounds : Array = [];
private var count : int = 0;
private var channel : SoundChannel;
public function musicOff () : void
{
if (channel != null)
{
channel.removeEventListener( Event.SOUND_COMPLETE, onSoundComplete );
channel.stop( );
channel = null;
}
}
public function musicOn () : void
{
if (sounds[count] == null) loadSound( );
else playLoadedSound( );
}
private function loadSound () : void
{
var sound : Sound = new Sound( );
sound.addEventListener( Event.COMPLETE, onSoundLoaded );
sound.load( new URLRequest( files[count] ) );
}
private function playLoadedSound () : void
{
channel = sounds[count].play( );
channel.addEventListener( Event.SOUND_COMPLETE, onSoundComplete );
}
private function onSoundComplete (ev : Event) : void
{
channel = null;
count++;
if (count >= files.length) count = 0;
musicOn( );
}
private function onSoundLoaded (ev : Event) : void
{
var snd : Sound = ev.target as Sound;
sounds.push( snd );
channel = snd.play( );
channel.addEventListener( Event.SOUND_COMPLETE, onSoundComplete );
}
public function SoundTest ()
{
musicOn( );
}
}
}
(顺便说一下,在加载声音之前你无法播放声音。这就是为什么你的脚本只有在重启后,当mp3在浏览器缓存中时才能工作。)