2014-09-18 4 views
-1

У меня есть 8 внешних mp3-файлов, которые загружаются и будут воспроизводиться последовательно. Я не могу понять, как приостановить воспроизведение mp3 и начать играть с того момента, когда он был приостановлен. У меня был код, который бы приостановил его, но при нажатии кнопки воспроизведения он будет воспроизводить первый mp3 с самого начала.AS3 Play & Pause Текущий (загруженный) MP3 (Flash CC)

var s1:Sound = new Sound(new URLRequest("Audio Files/1.mp3")); 
var s2:Sound = new Sound(new URLRequest("Audio Files/2.mp3")); 
var s3:Sound = new Sound(new URLRequest("Audio Files/3.mp3")); 
var s4:Sound = new Sound(new URLRequest("Audio Files/4.mp3")); 
var s5:Sound = new Sound(new URLRequest("Audio Files/5.mp3")); 
var s6:Sound = new Sound(new URLRequest("Audio Files/6.mp3")); 
var s7:Sound = new Sound(new URLRequest("Audio Files/7.mp3")); 
var s8:Sound = new Sound(new URLRequest("Audio Files/8.mp3")); 
s1.addEventListener(Event.COMPLETE, doLoadComplete); 
s2.addEventListener(Event.COMPLETE, doLoadComplete); 
s3.addEventListener(Event.COMPLETE, doLoadComplete); 
s4.addEventListener(Event.COMPLETE, doLoadComplete); 
s5.addEventListener(Event.COMPLETE, doLoadComplete); 
s6.addEventListener(Event.COMPLETE, doLoadComplete); 
s7.addEventListener(Event.COMPLETE, doLoadComplete); 
s8.addEventListener(Event.COMPLETE, doLoadComplete); 

var channel:SoundChannel = new SoundChannel(); 

channel = s1.play(); 
channel.addEventListener(Event.SOUND_COMPLETE, doSoundComplete); 


function doLoadComplete($evt:Event):void 
    { 
    trace("Song loaded."); 
    } 

function doSoundComplete($evt:Event):void 
    { 
    trace("1 done."); 
    channel = s2.play(); 
    channel.addEventListener(Event.SOUND_COMPLETE, doSoundComplete2) 
    } 

function doSoundComplete2($evt:Event):void 
    { 
    trace("2 done."); 
    channel = s3.play(); 
    channel.addEventListener(Event.SOUND_COMPLETE, doSoundComplete3); 
    }` 

Вот то, что я до сих пор: Это загружает mp3s и воспроизводит их. Пауза btn работает, но кнопка воспроизведения для возобновления звука дает мне ошибку: ReferenceError: Ошибка # 1069: Свойство 0 не найдено на flash.media.Sound и нет значения по умолчанию. at mp3sequence_fla :: MainTimeline/playSound() Я предполагаю, что значение для текущей позиции или последней позиции неверно.

var myArray:Array=[0,1,2,3,4,5,6,7]; 
var i:uint=1; 
var req:URLRequest = new URLRequest("mp3/"+myArray[i]+".mp3"); 
var VSound:Sound = new Sound(); 
var channel:SoundChannel = new SoundChannel(); 
var lastPosition:Number = 0; //last position of the sound 
var curSoundIndex:int = 0; //var to store the current sound that is playing 

VSound.load(req); 
channel = VSound.play(); 

function playSound(e:Event = null) { 
    //if no sound channel, load the current sound into it 
     channel = VSound[curSoundIndex].play(lastPosition); 
     channel.addEventListener(Event.SOUND_COMPLETE, doSoundComplete, false, 0, true); 
     lastPosition = channel.position; 
    } 
    function pauseSound(e:Event = null) { 
    if (channel) { 
     lastPosition = channel.position; 
     channel.stop(); 
    } 
} 

function doSoundComplete($evt:Event):void { 
    curSoundIndex++; 
    if (curSoundIndex >= VSound.length) curSoundIndex = 0; 
} 

play_btn.addEventListener(MouseEvent.CLICK, playSound); 
pause_btn.addEventListener(MouseEvent.CLICK, pauseSound); 
+0

Есть ли проблемы с ответом? – BadFeelingAboutThis

+0

Привет LDMS. Я думал, что это работает. Я не понимал, что мой оригинальный код похоронил в MC, который загружал mp3 и заставлял его казаться, что все mp3-файлы играли последовательно. Как только я удалил это и использовал только ваш код, воспроизводится только первый mp3. – DMC66

ответ

1

Чтобы приостановить звук, который вы можете сохранить это положение, когда Вы делаете паузу, и использовать эту переменную для воспроизведения с этой позиции.

var s:Sound = new Sound(new URLRequest("Audio Files/1.mp3")); 
var channel:SoundChannel = new SoundChannel(); 
channel = s.play(); 

var pausePosition:int; 
function pause():void { 
    soundPosition = channel.position; 
    channel.stop(); 
} 
function resume():void { 
    channel = s.play(soundPosition); 
} 
+0

не означал, чтобы сорвать ваш ответ, потребовалось некоторое время, чтобы напечатать мой, и ваш вошел в этот процесс. Я уйду оттуда, потому что он затрагивает некоторые другие проблемы OP. – BadFeelingAboutThis

+0

@LDMS Не беспокойтесь. Ваш ответ намного более полный. Я тоже думал о том, чтобы идти на все девять ярдов, но решил просто ответить на вопрос и двигаться дальше: P – Karmacon

+0

Thx Karma. Ваш код - это то, с чего я начал. Я не мог понять, как настроить таргетинг на mp3, который сейчас играет. Однако я ценю вашу помощь. спасибо! – DMC66

0

Вы можете сохранить position свойство соответствующего SoundChannel. Я добавил код, чтобы сделать все это менее избыточным

var curSoundIndex:int = 0; //var to store the current sound that is playing 
var lastPosition:Number = 0; //last position of the sound 
var soundChannel:SoundChannel; 
var sounds:Vector.<Sound> = new Vector.<Sound>(); //array of all sounds 

loadNextSound(); 

function loadNextSound(e:Event = null):void { 
    //check if all sounds are loaded 
    if (sounds.length >= 8) { 
     curSoundIndex = 0; //select first sound 
     resume(); //start playing 
     return; 
    } 

    //if not, load the next sound and add it to the array/vector 
    var sound:Sound = new Sound(new URLRequest("Audio Files/" + (sounds.length + 1) + ".mp3")); 
    sounds.push(sound); 
    if(sound.bytesLoaded < sound.bytesTotal){ //check if already loaded 
     sound.addEventListener(Event.COMPLETE, loadNextSound); 
    }else{ 
     loadNextSound(); 
    } 

} 

function pause(e:Event = null) { 
    if (soundChannel) { 
     lastPosition = soundChannel.position; 
     soundChannel.stop(); 
    } 
} 

function resume(e:Event = null) { 
    //if no sound channel, load the current sound into it 
     soundChannel = sounds[curSoundIndex].play(lastPosition); 
     soundChannel.addEventListener(Event.SOUND_COMPLETE, doSoundComplete, false, 0, true); //use weak listener to avoid memory leaks 
     lastPosition = 0; 
    } 
} 

function doSoundComplete($evt:Event):void { 
    curSoundIndex++; 
    if (curSoundIndex >= sounds.length) curSoundIndex = 0; 
} 
+0

thx LDMS. Меня просят развивать такие проекты каждые 12-18 месяцев. Мне нужно снова изучить AS3 снова. :) Я попробую ваш код и опубликую свой результат. Спасибо за помощь. – DMC66

+0

После настройки кнопок паузы и возобновления я получаю эту ошибку, когда я нажимаю для приостановки и возобновления. ArgumentError: ошибка # 1063: несоответствие счетчика аргументов в flow_test_fla :: testMC/resume(). Ожидаемое 0, получено 1. – DMC66

+0

Просто добавьте 'e: Event = null' в качестве аргумента функции возобновления и паузы, если вызывать его из прослушивателя событий (например, нажатие кнопки) – BadFeelingAboutThis

Смежные вопросы