Форум Flasher.ru

Форум Flasher.ru (http://www.flasher.ru/forum/index.php)
-   ActionScript 3.0 (http://www.flasher.ru/forum/forumdisplay.php?f=83)
-   -   Остановка всех звуков в игре (http://www.flasher.ru/forum/showthread.php?t=201916)

mihael_p 26.06.2013 11:26

Остановка всех звуков в игре
 
Всем добрый день! У меня в игре есть класс отвечающий за звуки, взят он отсюда: http://flashgameblogs.ru/blog/actionscript/557.html
Ситуация такова - есть раунд ограниченный по времени, и как только время заканчивается, нужно остановить все звуки ( героя, врагов). Единственное, что мне пришло в голову, вот это:

Код AS3:

public function removeAllSounds():void
{
        SoundMixer.stopAll();
        var len:int = mSoundChannels.length;
        for (var i:int = 0; i < len; i++)
        {
                var thisSoundChannel:SoundChannel = mSoundChannels[i] as SoundChannel;
                if (thisSoundChannel != null)
                {
                        thisSoundChannel.removeEventListener(Event.SOUND_COMPLETE, OnSFXComplete);
                        var idx:int = mSoundChannels.indexOf(thisSoundChannel);
                        mSoundChannels.splice(idx, 1);
                        soundTransforms.splice(idx, 1);
                        thisSoundChannel = null;
                }
        }
}

Но этот вариант не работает, почему то. Как быть в этой ситуации, посоветуйте, пожалуйста.

PsixokoT 26.06.2013 11:38

1) Вы идете циклом от начала массива и в нем же удаляете из него элементы, это не правильно!
2) У экземпляров SoundChannel есть метод stop()

belv 26.06.2013 11:45

http://help.adobe.com/ru_RU/FlashPla....html#stopAll() ,почитайте , может вам и не нужен цикл.

mihael_p 26.06.2013 11:52

Цитата:

Сообщение от PsixokoT (Сообщение 1139287)
1) Вы идете циклом от начала массива и в нем же удаляете из него элементы, это не правильно!

А как правильно, подскажите?

Цитата:

Сообщение от PsixokoT (Сообщение 1139287)
2) У экземпляров SoundChannel есть метод stop()

Сделал так:
Код AS3:

public function removeAllSounds():void
{
        SoundMixer.stopAll();
        var len:int = mSoundChannels.length;
        for (var i:int = 0; i < len; i++)
        {
                var thisSoundChannel:SoundChannel = mSoundChannels[i] as SoundChannel;
                if (thisSoundChannel != null)
                {
      thisSoundChannel.stop(); // остановка звука
                        thisSoundChannel.removeEventListener(Event.SOUND_COMPLETE, OnSFXComplete);
                        var idx:int = mSoundChannels.indexOf(thisSoundChannel);
                        mSoundChannels.splice(idx, 1);
                        soundTransforms.splice(idx, 1);
                        thisSoundChannel = null;
                }
        }
}

не помогло :(

Добавлено через 2 минуты
Цитата:

Сообщение от belv (Сообщение 1139289)
http://help.adobe.com/ru_RU/FlashPla....html#stopAll() ,почитайте , может вам и не нужен цикл.

В начале, перед циклом, стоит этот метод остановки, но он не помогает

belv 26.06.2013 12:02

Попробуйте протрейсить , какое значение выдаст?
var len:int = mSoundChannels.length;

C4Grey 26.06.2013 12:16

Советую попробовать что-то вроде такого: http://www.as3gamegears.com/sound/soundas/ . Или такого: http://www.as3gamegears.com/sound/sound-manager/ . Еще есть хороший вариант, но в нем не весь функционал может быть нужен в данной ситуации: http://aswebcreations.com/framework/.../soundmanager/

PsixokoT 26.06.2013 12:18

Код AS3:

public function removeAllSounds():void
{
        SoundMixer.stopAll();
        var thisSoundChannel:SoundChannel;
 
        while (mSoundChannels.length)
        {
                thisSoundChannel  = mSoundChannels.pop() as SoundChannel;
 
                if (thisSoundChannel)
                {
                        thisSoundChannel.stop(); // остановка звука
                        thisSoundChannel.removeEventListener(Event.SOUND_COMPLETE, OnSFXComplete);
                }
        }
        soundTransforms.splice(idx, soundTransforms.length); // soundTransforms = [];
}


mihael_p 26.06.2013 16:03

Странная ситуация,в функции removeAllSounds трейс перед while показывает, что длина массива равна 8, после while равна 0. Но, трейс в функции:

Код AS3:

private function OnSFXComplete(e:Event):void
{
        trace("Удалился");
        var thisSoundChannel:SoundChannel = e.currentTarget as SoundChannel;
        thisSoundChannel.removeEventListener(Event.SOUND_COMPLETE, OnSFXComplete);
        var idx:int = mSoundChannels.indexOf(thisSoundChannel);
        mSoundChannels.splice(idx, 1);
        soundTransforms.splice(idx, 1);
        thisSoundChannel = null;
}

срабатывает столько раз, сколько было элементов в массиве. Срабатывает после вызова функции removeAllSounds. Пробовал снимать слушателя - не помогает, звуки все равно проигрываются :(

in4core 27.06.2013 15:22

Не так давно на скорую руку писал, может быть и неочень хорошая реализация, но работать будет

Код AS3:

package com.in4core.utils 
{
        import flash.events.Event;
        import flash.media.Sound;
        import flash.media.SoundChannel;
        import flash.media.SoundTransform;
        import flash.utils.Dictionary;
        import flash.utils.setTimeout;
        /**
        * ...
        * @author in4core progression lab
        */

        public final class FastSoundManager
        {
                private static const _hash:Dictionary = new Dictionary(true);
                private static const _playedHash:Dictionary = new Dictionary(true);
 
                private static var _locker:Boolean = false;
 
                public static function addSoundToLibrary(sound:Sound , soundName:String):void
                {
                        _hash[soundName] = sound;
                }
 
                public static function addSounds(array:Array /* every element is array as [sound , soundName]*/):void
                {
                        for (var i:int = 0; i < array.length; i++)
                        {
                                _hash[ array[i][1] ] = array[i][0];
                        }
                }
 
                public static function playSound(soundName:String ,
                loop:Boolean = false , volume:Number = 1 , delayedCall:Number = 0):void
                {
                        if (_locker) return;
 
                        setTimeout(playSoundDelay, delayedCall , soundName , loop , volume);
                }
 
                private static function playSoundDelay(soundName:String , loop:Boolean = false , volume:Number = 1):void
                {
                        if (volume === 0) return;
 
                        var transform:SoundTransform = new SoundTransform(volume);
                        var soundChannel:SoundChannel = new SoundChannel();
                        var sound:Sound = _hash[ soundName ];
 
                        if (!sound) return;
 
                        soundChannel = sound.play(0, 0, transform);
 
                        if (loop) soundChannel.addEventListener(Event.SOUND_COMPLETE , onSoundComplete);
 
                        _playedHash[soundName] = [ sound , transform , soundChannel ];
                }
 
                public static function stopSound(soundName:String):void
                {
                        if (!_playedHash[soundName]) return;
 
                        var soundChannel:SoundChannel = _playedHash[soundName][2];
 
 
                        soundChannel.removeEventListener(Event.SOUND_COMPLETE , onSoundComplete);
                        soundChannel.stop();
                }
 
                public static function stopAllSounds():void
                {
                        for (var i:* in _playedHash)
                        {
                                stopSound(i);
                        }
                }
 
                public static function stopAllSoundsInsteadOf(sounds:Array):void
                {
                        for (var i:* in _playedHash)
                        {
                                if(sounds.indexOf(i) == -1) stopSound(i);
                        }
                }
 
                public static function lockAllSounds():void
                {
                        _locker = true;
 
                        stopAllSounds();
                }
 
                public static function unlockSounds():void
                {
                        _locker = false;
                }
 
                private static function onSoundComplete(e:Event):void
                {
                        var soundChannel:SoundChannel = e.currentTarget as SoundChannel;
                        soundChannel.removeEventListener(Event.SOUND_COMPLETE , onSoundComplete);
 
                        for (var i:* in _playedHash)
                        {
                                if ( _playedHash[i][2] == soundChannel)
                                {
                                        playSound( i , true , soundChannel.soundTransform.volume);
                                        return;
                                }
                        }
                }
 
                public static function get isLocked():Boolean
                {
                        return _locker;
                }
        }
}


mihael_p 27.06.2013 18:25

ого:) спасибо большое!


Часовой пояс GMT +4, время: 18:49.

Copyright © 1999-2008 Flasher.ru. All rights reserved.
Работает на vBulletin®. Copyright ©2000 - 2026, Jelsoft Enterprises Ltd. Перевод: zCarot
Администрация сайта не несёт ответственности за любую предоставленную посетителями информацию. Подробнее см. Правила.