예제 #1
0
 public void SetFlashing(int fadeRate, int fadeVariation, int flashRate, int flashVariation)
 {
     fadeMode = FadeMode.RandomFlashes;
     SetFading(fadeRate, fadeVariation);
     this.flashRate = flashRate;
     this.flashVariation = flashVariation;
 }
예제 #2
0
    private IEnumerator Fade(FadeMode fadeMode, float fadeTimer)
    {
        float timer = 0;
        float _fadeTimer = fadeTimer;

        while (timer < _fadeTimer)
        {
            switch (fadeMode)
            {
                case FadeMode.FadeIn:
                    FadeIn(_fadeTimer);
                    break;

                case FadeMode.FadeOut:
                    FadeOut(_fadeTimer);
                    break;
            }
            timer += Time.deltaTime;
            yield return new WaitForSeconds(0);
        }
    }
예제 #3
0
파일: Cue.cs 프로젝트: sethbattin/FNA
 internal void INTERNAL_startFadeOut(ushort ms)
 {
     INTERNAL_fadeStart = INTERNAL_timer.ElapsedMilliseconds;
     INTERNAL_fadeEnd   = ms;
     INTERNAL_fadeMode  = FadeMode.FadeOut;
 }
 /// <summary>
 /// 为`transition`创建一个状态(如果它还不存在),然后调用
 /// <see cref="Play(AnimancerState)"/> 或者 <see cref="Play(AnimancerState, float, FadeMode)"/>
 /// 依赖于 <see cref="ITransition.CrossFadeFromStart"/>.
 /// </summary>
 public AnimancerState Play(ITransition transition, float fadeDuration, FadeMode mode = FadeMode.FixedSpeed)
 {
     return(Playable.Play(transition, fadeDuration, mode));
 }
예제 #5
0
파일: Cue.cs 프로젝트: sethbattin/FNA
        internal bool INTERNAL_update()
        {
            // If we're not running, save some instructions...
            if (!INTERNAL_timer.IsRunning)
            {
                return(true);
            }

            // Play events when the timestamp has been hit.
            for (int i = 0; i < INTERNAL_eventList.Count; i += 1)
            {
                if (!INTERNAL_eventPlayed[i] &&
                    INTERNAL_timer.ElapsedMilliseconds > INTERNAL_eventList[i].Timestamp)
                {
                    uint type = INTERNAL_eventList[i].Type;
                    if (type == 1)
                    {
                        PlayWave((PlayWaveEvent)INTERNAL_eventList[i]);
                    }
                    else if (type == 2)
                    {
                        eventVolume = ((SetVolumeEvent)INTERNAL_eventList[i]).GetVolume();
                    }
                    else if (type == 3)
                    {
                        eventPitch = ((SetPitchEvent)INTERNAL_eventList[i]).GetPitch();
                    }
                    else
                    {
                        throw new Exception("Unhandled XACTEvent type!");
                    }
                    INTERNAL_eventPlayed[i] = true;
                }
            }

            // Clear out sound effect instances as they finish
            for (int i = 0; i < INTERNAL_instancePool.Count; i += 1)
            {
                if (INTERNAL_instancePool[i].State == SoundState.Stopped)
                {
                    // Get the event that spawned this instance...
                    PlayWaveEvent evt = (PlayWaveEvent)INTERNAL_waveEventSounds[INTERNAL_instancePool[i]];

                    // Then delete all the guff
                    INTERNAL_waveEventSounds.Remove(INTERNAL_instancePool[i]);
                    INTERNAL_instancePool[i].Dispose();
                    INTERNAL_instancePool.RemoveAt(i);
                    INTERNAL_instanceVolumes.RemoveAt(i);
                    INTERNAL_instancePitches.RemoveAt(i);
                    INTERNAL_rpcTrackVolumes.RemoveAt(i);
                    INTERNAL_rpcTrackPitches.RemoveAt(i);

                    // Increment the loop counter, try to get another loop
                    INTERNAL_eventLoops[evt] += 1;
                    PlayWave(evt);

                    // Removed a wave, have to step back...
                    i -= 1;
                }
            }

            // Fade in/out
            float fadePerc = 1.0f;

            if (INTERNAL_fadeMode != FadeMode.None)
            {
                if (INTERNAL_fadeMode == FadeMode.FadeOut)
                {
                    if (INTERNAL_category.crossfadeType == CrossfadeType.Linear)
                    {
                        fadePerc = (INTERNAL_fadeEnd - (INTERNAL_timer.ElapsedMilliseconds - INTERNAL_fadeStart)) / (float)INTERNAL_fadeEnd;
                    }
                    else
                    {
                        throw new NotImplementedException("Unhandled CrossfadeType!");
                    }
                    if (fadePerc <= 0.0f)
                    {
                        Stop(AudioStopOptions.Immediate);
                        INTERNAL_fadeMode = FadeMode.None;
                        return(false);
                    }
                }
                else
                {
                    if (INTERNAL_category.crossfadeType == CrossfadeType.Linear)
                    {
                        fadePerc = INTERNAL_timer.ElapsedMilliseconds / (float)INTERNAL_fadeEnd;
                    }
                    else
                    {
                        throw new NotImplementedException("Unhandled CrossfadeType!");
                    }
                    if (fadePerc > 1.0f)
                    {
                        fadePerc          = 1.0f;
                        INTERNAL_fadeMode = FadeMode.None;
                    }
                }
            }

            // User control updates
            if (INTERNAL_data.IsUserControlled)
            {
                string varName = INTERNAL_data.UserControlVariable;
                if (INTERNAL_userControlledPlaying &&
                    (INTERNAL_baseEngine.INTERNAL_isGlobalVariable(varName) ?
                     !MathHelper.WithinEpsilon(INTERNAL_controlledValue, INTERNAL_baseEngine.GetGlobalVariable(varName)) :
                     !MathHelper.WithinEpsilon(INTERNAL_controlledValue, GetVariable(INTERNAL_data.UserControlVariable))))
                {
                    // TODO: Crossfading
                    foreach (SoundEffectInstance sfi in INTERNAL_instancePool)
                    {
                        sfi.Stop();
                        sfi.Dispose();
                    }
                    INTERNAL_instancePool.Clear();
                    INTERNAL_instanceVolumes.Clear();
                    INTERNAL_instancePitches.Clear();
                    INTERNAL_rpcTrackVolumes.Clear();
                    INTERNAL_rpcTrackPitches.Clear();
                    if (!INTERNAL_calculateNextSound())
                    {
                        // Nothing to play, bail.
                        return(true);
                    }
                    INTERNAL_activeSound.GatherEvents(INTERNAL_eventList);
                    foreach (XACTEvent evt in INTERNAL_eventList)
                    {
                        INTERNAL_eventPlayed.Add(false);
                        INTERNAL_eventLoops.Add(evt, 0);
                    }
                    INTERNAL_timer.Stop();
                    INTERNAL_timer.Reset();
                    INTERNAL_timer.Start();
                }

                if (INTERNAL_activeSound == null)
                {
                    return(INTERNAL_userControlledPlaying);
                }
            }

            // If everything has been played and finished, we're done here.
            if (INTERNAL_instancePool.Count == 0)
            {
                bool allPlayed = true;
                foreach (bool played in INTERNAL_eventPlayed)
                {
                    if (!played)
                    {
                        allPlayed = false;
                        break;
                    }
                }
                if (allPlayed)
                {
                    // If this is managed, we're done completely.
                    if (INTERNAL_isManaged)
                    {
                        Dispose();
                    }
                    else
                    {
                        INTERNAL_timer.Stop();
                        INTERNAL_timer.Reset();
                        INTERNAL_category.INTERNAL_removeActiveCue(this);
                    }
                    return(INTERNAL_userControlledPlaying);
                }
            }

            // RPC updates
            float rpcVolume = 1.0f;
            float rpcPitch  = 0.0f;
            float hfGain    = 1.0f;
            float lfGain    = 1.0f;

            for (int i = 0; i < INTERNAL_activeSound.RPCCodes.Count; i += 1)
            {
                if (i > INTERNAL_instancePool.Count)
                {
                    break;
                }
                if (i > 0)
                {
                    INTERNAL_rpcTrackVolumes[i - 1] = 1.0f;
                    INTERNAL_rpcTrackPitches[i - 1] = 0.0f;
                }
                foreach (uint curCode in INTERNAL_activeSound.RPCCodes[i])
                {
                    RPC   curRPC = INTERNAL_baseEngine.INTERNAL_getRPC(curCode);
                    float result;
                    if (!INTERNAL_baseEngine.INTERNAL_isGlobalVariable(curRPC.Variable))
                    {
                        result = curRPC.CalculateRPC(GetVariable(curRPC.Variable));
                    }
                    else
                    {
                        // It's a global variable we're looking for!
                        result = curRPC.CalculateRPC(
                            INTERNAL_baseEngine.GetGlobalVariable(
                                curRPC.Variable
                                )
                            );
                    }
                    if (curRPC.Parameter == RPCParameter.Volume)
                    {
                        float vol = XACTCalculator.CalculateAmplitudeRatio(result / 100.0);
                        if (i == 0)
                        {
                            rpcVolume *= vol;
                        }
                        else
                        {
                            INTERNAL_rpcTrackVolumes[i - 1] *= vol;
                        }
                    }
                    else if (curRPC.Parameter == RPCParameter.Pitch)
                    {
                        float pitch = result / 1000.0f;
                        if (i == 0)
                        {
                            rpcPitch += pitch;
                        }
                        else
                        {
                            INTERNAL_rpcTrackPitches[i - 1] += pitch;
                        }
                    }
                    else if (curRPC.Parameter == RPCParameter.FilterFrequency)
                    {
                        // FIXME: Just listening to the last RPC!
                        float hf = result / 20000.0f;
                        float lf = 1.0f - hf;
                        if (i == 0)
                        {
                            hfGain = hf;
                            lfGain = lf;
                        }
                        else
                        {
                            throw new NotImplementedException("Per-track filter RPCs!");
                        }
                    }
                    else
                    {
                        throw new Exception("RPC Parameter Type: " + curRPC.Parameter.ToString());
                    }
                }
            }

            // Sound effect instance updates
            for (int i = 0; i < INTERNAL_instancePool.Count; i += 1)
            {
                /* The final volume should be the combination of the
                 * authored volume, category volume, RPC/Event volumes, and fade.
                 */
                INTERNAL_instancePool[i].Volume = (
                    INTERNAL_instanceVolumes[i] *
                    INTERNAL_category.INTERNAL_volume.Value *
                    rpcVolume *
                    INTERNAL_rpcTrackVolumes[i] *
                    eventVolume *
                    fadePerc
                    );

                /* The final pitch should be the combination of the
                 * authored pitch and RPC/Event pitch results.
                 */
                INTERNAL_instancePool[i].Pitch = (
                    INTERNAL_instancePitches[i] +
                    rpcPitch +
                    eventPitch +
                    INTERNAL_rpcTrackPitches[i]
                    );

                /* The final filter is determined by the instance's filter type,
                 * in addition to our calculation of the HF/LF gain values.
                 */
                byte fType = INTERNAL_instancePool[i].FilterType;
                if (fType == 0xFF)
                {
                    // No-op, no filter!
                }
                else if (fType == 0)
                {
                    INTERNAL_instancePool[i].INTERNAL_applyLowPassFilter(hfGain);
                }
                else if (fType == 1)
                {
                    INTERNAL_instancePool[i].INTERNAL_applyHighPassFilter(lfGain);
                }
                else if (fType == 2)
                {
                    INTERNAL_instancePool[i].INTERNAL_applyBandPassFilter(hfGain, lfGain);
                }
                else
                {
                    throw new InvalidOperationException("Unhandled filter type!");
                }

                // Update 3D position, if applicable
                if (INTERNAL_isPositional)
                {
                    INTERNAL_instancePool[i].Apply3D(
                        INTERNAL_listener,
                        INTERNAL_emitter
                        );
                }
            }

            return(true);
        }
예제 #6
0
        /*! \cond PRIVATE */
        /// <summary>
        /// Never call this method. Used internally.
        /// </summary>
        /// <param name="pitch">Pitch.</param>
        /// <param name="maxVolume">Max volume.</param>
        /// <param name="gameObjectName">Game object name.</param>
        /// <param name="volPercent">Vol percent.</param>
        /// <param name="targetVol">Target vol.</param>
        /// <param name="targetPitch">Target pitch.</param>
        /// <param name="sourceTrans">Source trans.</param>
        /// <param name="attach">If set to <c>true</c> attach.</param>
        /// <param name="delayTime">Delay time.</param>
        /// <param name="timeToSchedulePlay"><b>Optional</b> - used to pass in the DSP time to play the sound. Play now if null.</param>
        /// <param name="isChaining">If set to <c>true</c> is chaining.</param>
        /// <param name="isSingleSubscribedPlay">If set to <c>true</c> is single subscribed play.</param>
        public void Play(float?pitch, float maxVolume, string gameObjectName, float volPercent, float targetVol,
                         float?targetPitch, Transform sourceTrans, bool attach, float delayTime,
                         double?timeToSchedulePlay, bool isChaining, bool isSingleSubscribedPlay)
        {
            if (!MasterAudio.IsWarming && audLocation == MasterAudio.AudioLocation.FileOnInternet)
            {
                switch (internetFileLoadStatus)
                {
                case MasterAudio.InternetFileLoadStatus.Loading:
                    if (ParentGroup.LoggingEnabledForGroup)
                    {
                        MasterAudio.LogWarning("Cannot play Variation '" + name +
                                               "' because its Internet file has not been downloaded yet.");
                    }
                    return;

                case MasterAudio.InternetFileLoadStatus.Failed:
                    if (ParentGroup.LoggingEnabledForGroup)
                    {
                        MasterAudio.LogWarning("Cannot play Variation '" + name +
                                               "' because its Internet file failed downloading.");
                    }
                    return;
                }
            }

            MaybeCleanupFinishedDelegate();
            _hasStartedEndLinkedGroups = false;
            _isPaused = false;

            SetPlaySoundParams(gameObjectName, volPercent, targetVol, targetPitch, sourceTrans, attach, delayTime, timeToSchedulePlay, isChaining, isSingleSubscribedPlay);

            SetPriority(); // reset it back to normal priority in case you're playing 2D this time.

            if (MasterAudio.HasAsyncResourceLoaderFeature() && ShouldLoadAsync)
            {
                StopAllCoroutines(); // The only Coroutine right now requires pro version and Unity 4.5.3
            }

            // compute pitch
            if (pitch.HasValue)
            {
                VarAudio.pitch = pitch.Value;
            }
            else if (useRandomPitch)
            {
                var randPitch = Random.Range(randomPitchMin, randomPitchMax);

                switch (randomPitchMode)
                {
                case RandomPitchMode.AddToClipPitch:
                    randPitch += OriginalPitch;
                    break;
                }

                VarAudio.pitch = randPitch;
            }
            else
            {
                // non random pitch
                VarAudio.pitch = OriginalPitch;
            }

#if UNITY_5 || UNITY_2017_1_OR_NEWER
            // in case it was changed at runtime.
            SetSpatialBlend();
#endif

            // set fade mode
            curFadeMode      = FadeMode.None;
            curPitchMode     = PitchMode.None;
            curDetectEndMode = DetectEndMode.DetectEnd;
            _maxVol          = maxVolume;
            if (maxCustomLoops == minCustomLoops)
            {
                _maxLoops = minCustomLoops;
            }
            else
            {
                _maxLoops = Random.Range(minCustomLoops, maxCustomLoops + 1);
            }

            switch (audLocation)
            {
            case MasterAudio.AudioLocation.Clip:
                FinishSetupToPlay();
                return;

            case MasterAudio.AudioLocation.ResourceFile:
                if (MasterAudio.HasAsyncResourceLoaderFeature() && ShouldLoadAsync)
                {
                    StartCoroutine(AudioResourceOptimizer.PopulateSourcesWithResourceClipAsync(ResFileName, this,
                                                                                               FinishSetupToPlay, ResourceFailedToLoad));
                }
                else
                {
                    if (!AudioResourceOptimizer.PopulateSourcesWithResourceClip(ResFileName, this))
                    {
                        return;     // audio file not found!
                    }

                    FinishSetupToPlay();
                }
                return;

            case MasterAudio.AudioLocation.FileOnInternet:
                FinishSetupToPlay();
                return;
            }
        }
예제 #7
0
 /// <summary>
 /// Provides an amplitudemultiplyer for fading
 /// </summary>
 /// <param name="x">Time-Input, scaled from 0...1 (start fade...finish)</param>
 /// <param name="mode">FadeMode to use</param>
 /// <returns>Multiplier ranging from 1...0</returns>
 protected double FadeGen(double x, FadeMode mode)
 {
     x = Math.Min(1, Math.Max(0, x));//Crop to 0...1 range
     switch (mode)
     {
         default:
         case FadeMode.None:
             return 1;
         case FadeMode.Quadratic:
             return -1 * x * x + 1;
         case FadeMode.Cubical:
             return -1 * x * x * x + 1;
         case FadeMode.Smooth:
             var u = (2 * x - 1)/Sqrt3;
             var v = u*u*u;
             return 0.75 * Sqrt3 * (v - u) + 0.5;
         case FadeMode.Linear:
             return 1 - x;
         case FadeMode.Circle:
             return Math.Sqrt(1 - (x * x));
     }
 }
예제 #8
0
    /// <summary>
    /// This method allows you to pause the audio being played by this Variation. This is automatically called by MasterAudio.PauseSoundGroup and MasterAudio.PauseBus.
    /// </summary>
    public void Pause()
    {
        if (audLocation == MasterAudio.AudioLocation.ResourceFile && !MasterAudio.Instance.resourceClipsPauseDoNotUnload) {
            Stop();
            return;
        }

        VarAudio.Pause();
        this.curFadeMode = FadeMode.None;
        if (VariationUpdater != null) {
            VariationUpdater.StopWaitingForFinish(); // necessary so that the clip can be unpaused.
        }

        MaybeUnloadClip();
    }
예제 #9
0
    /// <summary>
    /// This method allows you to fade the sound from this Variation to a specified volume over X seconds.
    /// </summary>
    /// <param name="newVolume">The target volume to fade to.</param>
    /// <param name="fadeTime">The time it will take to fully fade to the target volume.</param>
    public void FadeToVolume(float newVolume, float fadeTime)
    {
        this.curFadeMode = FadeMode.GradualFade;
		
        StartCoroutine(FadeOverTimeToVolume(newVolume, fadeTime));
    }
    void Awake()
    {
        this.useGUILayout = false;
        duckingMode = AudioDuckingMode.NotDucking;
        currentSong = null;
        songsPlayedFromPlaylist = 0;

        var audios = this.GetComponents<AudioSource>();
        if (audios.Length < 2)
        {
            Debug.LogError("This prefab should have exactly two Audio Source components. Please revert it.");
            return;
        }

        AudioSource audio1 = audios[0];
        AudioSource audio2 = audios[1];

        audio1.clip = null;
        audio2.clip = null;

        activeAudio = audio1;
        transitioningAudio = audio2;
        go = this.gameObject;
        curFadeMode = FadeMode.None;
        fadeCompleteCallback = null;
    }
예제 #11
0
        /// <summary>
        /// Triggers fading out the target UI element.
        /// </summary>
        public void FadeOut()
        {
            if (currentState != FadeMode.Out)
            {
                currentState = FadeMode.Out;
                timer        = 0f;
            }

            timer += Time.deltaTime;

            switch (componentType)
            {
            case ComponentType.CanvasGroup:     // Canvas Group
                if (canvasGroup.alpha != 0f)
                {
                    canvasGroup.alpha = Mathf.Lerp(1f, 0f, timer / fadeTime);
                }
                else if (mode == FadeMode.PingPong)
                {
                    FadeIn();
                }
                else if (destroyOnFadeOut)
                {
                    Destroy(gameObject);
                }
                else
                {
                    mode = FadeMode.None;
                }
                break;

            case ComponentType.Image:     // Image
                if (image.color != fadeOutColor)
                {
                    image.color = Color.Lerp(defaultColor, fadeOutColor, timer / fadeTime);
                }
                else if (mode == FadeMode.PingPong)
                {
                    FadeIn();
                }
                else if (destroyOnFadeOut)
                {
                    Destroy(gameObject);
                }
                else
                {
                    mode = FadeMode.None;
                }
                break;

            case ComponentType.Text:     // Text
                if (text.color != fadeOutColor)
                {
                    text.color = Color.Lerp(defaultColor, fadeOutColor, timer / fadeTime);
                }
                else if (mode == FadeMode.PingPong)
                {
                    FadeIn();
                }
                else if (destroyOnFadeOut)
                {
                    Destroy(gameObject);
                }
                else
                {
                    mode = FadeMode.None;
                }
                break;
            }
        }
예제 #12
0
 public void Fade(FadeMode fadeModeOption)
 {
     fadeMode = fadeModeOption;
     fade     = true;
 }
    IEnumerator CoUpdate()
    {
        while (true)
        {
            yield return new WaitForSeconds(MasterAudio.INNER_LOOP_CHECK_INTERVAL);

            // gradual fade code
            if (curFadeMode != FadeMode.GradualFade)
            {
                continue;
            }

            if (activeAudio == null)
            {
                continue; // paused or error in setup
            }

            var newVolume = PlaylistVolume + slowFadeVolStep; 
			
            if (slowFadeVolStep > 0f)
            {
                newVolume = Math.Min(newVolume, slowFadeTargetVolume);
            }
            else
            {
                newVolume = Math.Max(newVolume, slowFadeTargetVolume);
            }

            playlistVolume = newVolume / MasterAudio.PlaylistMasterVolume;
			
            UpdateMasterVolume();

            if (newVolume == slowFadeTargetVolume)
            {
                if (fadeCompleteCallback != null)
                {
                    fadeCompleteCallback();
                    fadeCompleteCallback = null;
                }
                curFadeMode = FadeMode.None;
            }
        }
    }
예제 #14
0
 /// <summary>
 /// フェードモードを設定
 /// </summary>
 /// <param name="fade">フェードの種類</param>
 private void SetFadeMode(FadeMode fade)
 {
     GetComponent <Image>().material.SetFloat("_FadeMode", (float)fade);
 }
 public FadeFilter(FadeMode fadeMode, double duration, double startSeconds = 0)
 {
     FadeMode     = fadeMode;
     Duration     = duration;
     StartSeconds = startSeconds;
 }
예제 #16
0
    /// <summary>
    /// This method allows you to fade the sound from this Variation to a specified volume over X seconds.
    /// </summary>
    /// <param name="newVolume">The target volume to fade to.</param>
    /// <param name="fadeTime">The time it will take to fully fade to the target volume.</param>
    public void FadeToVolume(float newVolume, float fadeTime)
    {
        this.curFadeMode = FadeMode.GradualFade;

        StartCoroutine(FadeOverTimeToVolume(newVolume, fadeTime));
    }
예제 #17
0
    void Awake()
    {
        // check for "extra" Playlist Controllers of the same name.
        var controllers = (PlaylistController[]) GameObject.FindObjectsOfType(typeof(PlaylistController));
        var sameNameCount = 0;

        for (var i = 0; i < controllers.Length; i++) {
            if (controllers[i].gameObject.name == gameObject.name) {
                sameNameCount++;
            }
        }

        if (sameNameCount > 1) {
            Destroy(gameObject);
            Debug.Log("More than one Playlist Controller prefab exists in this Scene with the same name. Destroying the one called '" + this.name + "'. You may wish to set up a Bootstrapper Scene so this does not occur.");
            return;
        }
        // end check

        this.useGUILayout = false;
        duckingMode = AudioDuckingMode.NotDucking;
        currentSong = null;
        songsPlayedFromPlaylist = 0;

        var audios = this.GetComponents<AudioSource>();
        if (audios.Length < 2)
        {
            Debug.LogError("This prefab should have exactly two Audio Source components. Please revert it.");
            return;
        }

        AudioSource audio1 = audios[0];
        AudioSource audio2 = audios[1];

        audio1.clip = null;
        audio2.clip = null;

        activeAudio = audio1;
        transitioningAudio = audio2;
        go = this.gameObject;
        curFadeMode = FadeMode.None;
        fadeCompleteCallback = null;
    }
예제 #18
0
    /// <summary>
    /// This method allows you to pause the audio being played by this Variation. This is automatically called by MasterAudio.PauseSoundGroup and MasterAudio.PauseBus.
    /// </summary>
    public void Pause()
    {
        if (audLocation == MasterAudio.AudioLocation.ResourceFile && !MasterAudio.Instance.resourceClipsPauseDoNotUnload)
        {
            Stop();
            return;
        }

        _audio.Pause();
        this.curFadeMode = FadeMode.None;

        MaybeUnloadClip();
    }
예제 #19
0
        public override void OnInspectorGUI()
        {
            serializedObject.Update();

            var uniFader = serializedObject.targetObject as UniFader;

            using (new EditorGUI.DisabledScope(true))
            {
                EditorGUILayout.PropertyField(m_Script);
            }

            EditorGUILayout.PropertyField(usedAsInstance);

            if (CheckIfMultiFaderHasDefaultSettings())
            {
                EditorGUILayout.HelpBox("There are some UniFader marked as \"Used By Default\". One of them is used by static functions at random.", MessageType.Warning);
            }

            EditorGUILayout.PropertyField(fadeTarget);
            EditorGUILayout.PropertyField(defaultDuration);

            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.PropertyField(fadeOutCurve);
                ShowContextButton("Copy Mirror Curve To Fade In", fadeOutCurve);
            }

            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.PropertyField(fadeInCurve);
                ShowContextButton("Copy Mirror Curve To Fade Out", fadeInCurve);
            }

            EditorGUILayout.PropertyField(sortingOrder);
            EditorGUILayout.PropertyField(ignoreTimeScale);

            DrawUtility.DrawSeparator(3);

            // create fade pattern menu
            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.PrefixLabel("Fade Pattern");
                if (GUILayout.Button(fadePattern.type, "MiniPopup"))
                {
                    var menu  = new GenericMenu();
                    var names = TypeUtility.GetAllFadePatternNames <IFadePattern>();

                    for (var i = 0; i < names.Length; ++i)
                    {
                        var idx = i;
                        menu.AddItem(new GUIContent(names[i]), false,
                                     () =>
                        {
                            if (fadePattern.type == names[idx])
                            {
                                return;
                            }

                            // Type.GetType doesn't work
                            Undo.RegisterCompleteObjectUndo(uniFader, "Change Fade Pattern");
                            var fadeType         = TypeUtility.GetTypeByName(names[idx]);
                            var fadeInstance     = (IFadePattern)Activator.CreateInstance(fadeType);
                            uniFader.FadePattern = fadeInstance;

                            var image      = (fadeTarget.objectReferenceValue as System.Object) as Image;
                            image.material = null;
                        });
                    }
                    menu.ShowAsContext();
                }
            }

            DrawFaderItem(fadePattern);

            // Draw preview button
            using (new EditorGUILayout.VerticalScope("box"))
            {
                var titleLabel = Application.isPlaying ? "Debug" : "Debug (Runtime Only)";
                GUILayout.Label(titleLabel, EditorStyles.boldLabel);

                EditorGUI.BeginDisabledGroup(!Application.isPlaying);
                EditorGUILayout.BeginHorizontal();

                if (GUILayout.Button("Preview:", GUILayout.Width(EditorGUIUtility.labelWidth)))
                {
                    switch (fadeMode)
                    {
                    case FadeMode.FadeIn:    uniFader.FadeIn();    break;

                    case FadeMode.FadeOut:   uniFader.FadeOut();   break;

                    case FadeMode.FadeInOut: uniFader.FadeIn(() => uniFader.FadeOut()); break;

                    case FadeMode.FadeOutIn: uniFader.FadeOut(() => uniFader.FadeIn()); break;
                    }
                }

                fadeMode = (FadeMode)EditorGUILayout.EnumPopup(fadeMode);

                EditorGUI.EndDisabledGroup();
                EditorGUILayout.EndHorizontal();
            }

            EditorGUILayout.PropertyField(onFadeOut);
            EditorGUILayout.PropertyField(onFadeIn);

            serializedObject.ApplyModifiedProperties();
        }
예제 #20
0
    /// <summary>
    /// This method is called automatically from MasterAudio.PlaySound and MasterAudio.PlaySound3D. 
    /// </summary>
    /// <param name="maxVolume">If fade in time is not zero on this Variation, max volume is the fully faded in clip's target volume. Otherwise this is not used.</param>
    public void Play(float? pitch, float maxVolume, PlaySoundParams playParams = null)
    {
        SoundFinished = null; // clear it out so subscribers don't have to clean up
        isWaitingForDelay = false;
        playSndParams = playParams;

        // compute pitch
        if (pitch.HasValue)
        {
            _audio.pitch = pitch.Value;
        }
        else
        {
            var randPitch = 0f;

            if (randomPitch != 0f)
            {
                randPitch = UnityEngine.Random.Range(-randomPitch, randomPitch);
            }
            _audio.pitch = OriginalPitch + randPitch;
        }

        // set fade mode
        this.curFadeMode = FadeMode.None;
        curDetectEndMode = DetectEndMode.DetectEnd;

        if (audLocation == MasterAudio.AudioLocation.ResourceFile)
        {
            AudioResourceOptimizer.PopulateSourcesWithResourceClip(resourceFileName);
        }

        StopAllCoroutines();
        timesLocationUpdated = 0;

        if (!_audio.isPlaying && _audio.time > 0f)
        {
            // paused. Do nothing except Play
        }
        else if (useFades && (fadeInTime > 0f || fadeOutTime > 0f))
        {
            fadeMaxVolume = maxVolume;
            _audio.volume = 0f;
            StartCoroutine(FadeInOut());
        }

        if (playSndParams != null && playSndParams.isChainLoop)
        {
            _audio.loop = false;
        }

        ParentGroup.AddActiveAudioSourceId(this);

        StartCoroutine(DetectSoundFinished(playParams.delaySoundTime));

        attachToSource = false;

        bool useClipAgePriority = MasterAudio.Instance.prioritizeOnDistance && (MasterAudio.Instance.useClipAgePriority || ParentGroup.useClipAgePriority);
        if (playParams.attachToSource || useClipAgePriority) {
            attachToSource = playParams.attachToSource;
            StartCoroutine(FollowSoundMaker());
        }
    }
예제 #21
0
    /// <summary>
    /// This method is called automatically from MasterAudio.PlaySound and MasterAudio.PlaySound3D. 
    /// </summary>
    /// <param name="maxVolume">If fade in time is not zero on this Variation, max volume is the fully faded in clip's target volume. Otherwise this is not used.</param>
    public void Play(float? pitch, float maxVolume, PlaySoundParams playParams = null)
    {
        SoundFinished = null; // clear it out so subscribers don't have to clean up
        isWaitingForDelay = false;
		playSndParams = playParams;

        // compute pitch
        if (pitch.HasValue) {
            VarAudio.pitch = pitch.Value;
        } else if (useRandomPitch) {
            var randPitch = UnityEngine.Random.Range(randomPitchMin, randomPitchMax);
            
			switch (randomPitchMode) {
				case RandomPitchMode.AddToClipPitch:
					randPitch += OriginalPitch;
					break;
			}
			
			VarAudio.pitch = randPitch;
        } else { // non random pitch
			VarAudio.pitch = OriginalPitch;
		}

        // set fade mode
        this.curFadeMode = FadeMode.None;
        curDetectEndMode = DetectEndMode.DetectEnd;
		_maxVol = maxVolume;

        StopAllCoroutines();
		
        if (audLocation == MasterAudio.AudioLocation.Clip) {
			FinishSetupToPlay();
			return;
		}
		
		AudioResourceOptimizer.PopulateSourcesWithResourceClip(resourceFileName, this);
		
		if (audLocation == MasterAudio.AudioLocation.ResourceFile) {
			FinishSetupToPlay();
		}
    }
예제 #22
0
    private IEnumerator FadeInOut()
    {
        var fadeOutStartTime = _audio.clip.length - (fadeOutTime * _audio.pitch);

        yield return new WaitForSeconds(MasterAudio.INNER_LOOP_CHECK_INTERVAL); // wait for the clip to start playing :)

        var stepVolumeUp = fadeMaxVolume / fadeInTime * MasterAudio.INNER_LOOP_CHECK_INTERVAL;

        curFadeMode = FadeMode.FadeInOut; // wait to set this so it stops the previous one if it's still going.

        if (fadeInTime > 0f)
        {
            while (_audio.isPlaying && curFadeMode == FadeMode.FadeInOut && _audio.time < fadeInTime)
            {
                _audio.volume += stepVolumeUp;
                yield return new WaitForSeconds(MasterAudio.INNER_LOOP_CHECK_INTERVAL);
            }
        }

        if (curFadeMode != FadeMode.FadeInOut)
        {
            yield break; // in case another fade cancelled this one
        }

        _audio.volume = fadeMaxVolume; // just in case it didn't align exactly

        if (fadeOutTime == 0f || _audio.loop)
        {
            yield break; // nothing more to do!
        }

        // wait for fade out time.
        while (_audio.isPlaying && curFadeMode == FadeMode.FadeInOut && _audio.time < fadeOutStartTime)
        {
            yield return new WaitForSeconds(MasterAudio.INNER_LOOP_CHECK_INTERVAL);
        }

        if (curFadeMode != FadeMode.FadeInOut)
        {
            yield break; // in case another fade cancelled this one
        }

        var stepVolumeDown = fadeMaxVolume / fadeOutTime * MasterAudio.INNER_LOOP_CHECK_INTERVAL;

        while (_audio.isPlaying && curFadeMode == FadeMode.FadeInOut)
        {
            _audio.volume -= stepVolumeDown;
            yield return new WaitForSeconds(MasterAudio.INNER_LOOP_CHECK_INTERVAL);
        }

        audio.volume = 0f;
        Stop();

        if (curFadeMode != FadeMode.FadeInOut)
        {
            yield break; // in case another fade cancelled this one
        }

        curFadeMode = FadeMode.None;
    }
예제 #23
0
    private IEnumerator FadeOutEarly(float fadeTime)
    {
        curFadeMode = FadeMode.FadeOutEarly; // cancel the FadeInOut loop, if it's going.

        var stepVolumeDown = VarAudio.volume / fadeTime * MasterAudio.INNER_LOOP_CHECK_INTERVAL;

        while (VarAudio.isPlaying && curFadeMode == FadeMode.FadeOutEarly && VarAudio.volume > 0)
        {
            VarAudio.volume -= stepVolumeDown;

			if (MasterAudio.IgnoreTimeScale) { 
				yield return StartCoroutine(CoroutineHelper.WaitForActualSeconds(MasterAudio.INNER_LOOP_CHECK_INTERVAL));
			} else {
				yield return MasterAudio.InnerLoopDelay;
			}
        }

        VarAudio.volume = 0f;
        Stop();

        if (curFadeMode != FadeMode.FadeOutEarly)
        {
            yield break; // in case another fade cancelled this one
        }

        curFadeMode = FadeMode.None;
    }
예제 #24
0
파일: Cue.cs 프로젝트: clarvalon/FNA
		internal void INTERNAL_startFadeIn(ushort ms)
		{
			// start is not used, since it's always 0 anyway -flibit
			INTERNAL_fadeEnd = ms;
			INTERNAL_fadeMode = FadeMode.FadeIn;
		}
예제 #25
0
        /************************************************************************************************************************/

        /// <summary>
        /// Starts fading in the `clip` over the course of the `fadeDuration` while fading out all others in the same
        /// layer. Returns its state.
        /// <para></para>
        /// If the `state` was already playing and fading in with less time remaining than the `fadeDuration`, this
        /// method will allow it to complete the existing fade rather than starting a slower one.
        /// <para></para>
        /// If the layer currently has 0 <see cref="AnimancerNode.Weight"/>, this method will fade in the layer itself
        /// and simply <see cref="AnimancerState.Play(AnimationClip)"/> the `clip`.
        /// <para></para>
        /// Animancer Lite only allows the default `fadeDuration` (0.25 seconds) in a runtime build.
        /// </summary>
        public AnimancerState Play(AnimationClip clip, float fadeDuration, FadeMode mode = FadeMode.FixedSpeed)
        {
            return(Play(States.GetOrCreate(clip), fadeDuration, mode));
        }
예제 #26
0
        private PicassoDrawable(Context context, Bitmap bitmap, Drawable placeholder, LoadedFrom loadedFrom, FadeMode fadeMode)
            : base(context.Resources, bitmap)
        {
            bool fade = fadeMode == FadeMode.Always ||
                        (loadedFrom != LoadedFrom.Memory && fadeMode == FadeMode.NotFromMemory);

            if (fade)
            {
                m_Placeholder     = placeholder;
                m_Animating       = true;
                m_StartTimeMillis = SystemClock.UptimeMillis();
            }
        }
예제 #27
0
    private IEnumerator FadeOutEarly(float fadeTime)
    {
        curFadeMode = FadeMode.FadeOutEarly; // cancel the FadeInOut loop, if it's going.

        var stepVolumeDown = _audio.volume / fadeTime * MasterAudio.INNER_LOOP_CHECK_INTERVAL;

        while (_audio.isPlaying && curFadeMode == FadeMode.FadeOutEarly)
        {
            _audio.volume -= stepVolumeDown;
            yield return new WaitForSeconds(MasterAudio.INNER_LOOP_CHECK_INTERVAL);
        }

        _audio.volume = 0f;
        Stop();

        if (curFadeMode != FadeMode.FadeOutEarly)
        {
            yield break; // in case another fade cancelled this one
        }

        curFadeMode = FadeMode.None;
    }
예제 #28
0
 public RequestCreator FadeMode(FadeMode mode)
 {
     m_FadeMode = mode;
     return(this);
 }
예제 #29
0
    /// <summary>
    /// Fades the window out.
    /// </summary>
    /// <param name="duration">Fade Out duration.</param>
    private void FadeOut(float duration) {
        if (!ContentHolder.gameObject.activeSelf) {
            return;
        }

        if (_currentFadeMode == FadeMode.Out) {
            // ignore command if we are already actively fading out
            D.AssertNotNull(_fadeOutJob);
            return;
        }

        if (_currentFadeMode == FadeMode.In) {
            D.AssertNotNull(_fadeInJob);
            KillFadeInJob();
            _currentFadeMode = FadeMode.None;
        }

        string jobName = "{0}.FadeOutJob".Inject(DebugName);    // no pause controls on fadeJob as I want window access while paused
        _fadeOutJob = _jobMgr.StartNonGameplayJob(FadeAnimation(FadeMode.Out, duration), jobName, jobCompleted: (jobWasKilled) => {
            if (jobWasKilled) {
                // 12.12.16 An AssertNull(_jobRef) here can fail as the reference can refer to a new Job, created 
                // right after the old one was killed due to the 1 frame delay in execution of jobCompleted(). My attempts at allowing
                // the AssertNull to occur failed. I believe this is OK as _jobRef is nulled from KillXXXJob() and, if 
                // the reference is replaced by a new Job, then the old Job is no longer referenced which is the objective. Jobs Kill()ed
                // centrally by JobManager won't null the reference, but this only occurs during scene transitions.
                ////__ValidateKilledFadeJobReference(_fadeOutJob);
            }
            else {
                _fadeOutJob = null;
            }
        });
    }
예제 #30
0
    private IEnumerator FadeOverTimeToVolume(float targetVolume, float fadeTime)
    {
        if (fadeTime <= MasterAudio.INNER_LOOP_CHECK_INTERVAL)
        {
            _audio.volume = targetVolume; // time really short, just do it at once.
            if (_audio.volume <= 0f)
            {
                Stop();
            }
            curFadeMode = FadeMode.None;
            yield break;
        }

        yield return new WaitForSeconds(MasterAudio.INNER_LOOP_CHECK_INTERVAL); // wait for the clip to start playing :)

        var volStep = (targetVolume - _audio.volume) / (fadeTime / MasterAudio.INNER_LOOP_CHECK_INTERVAL);
        float newVol;
        while (_audio.volume != targetVolume && curFadeMode == FadeMode.GradualFade)
        {
            newVol = _audio.volume + volStep;

            if (volStep > 0f)
            {
                newVol = Math.Min(newVol, targetVolume);
            }
            else
            {
                newVol = Math.Max(newVol, targetVolume);
            }

            _audio.volume = newVol;

            yield return new WaitForSeconds(MasterAudio.INNER_LOOP_CHECK_INTERVAL); // wait for the clip to start playing :)
        }

        if (_audio.volume <= 0f)
        {
            Stop();
        }

        if (curFadeMode != FadeMode.GradualFade)
        {
            yield break; // in case another fade cancelled this one
        }

        curFadeMode = FadeMode.None;
    }
예제 #31
0
        /*! \cond PRIVATE */
        /// <summary>
        /// Never call this method. Used internally.
        /// </summary>
        /// <param name="pitch">Pitch.</param>
        /// <param name="maxVolume">Max volume.</param>
        /// <param name="gameObjectName">Game object name.</param>
        /// <param name="volPercent">Vol percent.</param>
        /// <param name="targetVol">Target vol.</param>
        /// <param name="targetPitch">Target pitch.</param>
        /// <param name="sourceTrans">Source trans.</param>
        /// <param name="attach">If set to <c>true</c> attach.</param>
        /// <param name="delayTime">Delay time.</param>
        /// <param name="timeToSchedulePlay"><b>Optional</b> - used to pass in the DSP time to play the sound. Play now if null.</param>
        /// <param name="isChaining">If set to <c>true</c> is chaining.</param>
        /// <param name="isSingleSubscribedPlay">If set to <c>true</c> is single subscribed play.</param>
        public void Play(float?pitch, float maxVolume, string gameObjectName, float volPercent, float targetVol,
                         float?targetPitch, Transform sourceTrans, bool attach, float delayTime,
                         double?timeToSchedulePlay, bool isChaining, bool isSingleSubscribedPlay)
        {
            LoadStatus       = MasterAudio.VariationLoadStatus.None;
            _isStopRequested = false;
            _isWarmingPlay   = MasterAudio.IsWarming;

            MaybeCleanupFinishedDelegate();
            _hasStartedEndLinkedGroups = false;
            _isPaused = false;

            SetPlaySoundParams(gameObjectName, volPercent, targetVol, targetPitch, sourceTrans, attach, delayTime, timeToSchedulePlay, isChaining, isSingleSubscribedPlay);

            SetPriority(); // reset it back to normal priority in case you're playing 2D this time.

            // compute pitch
            if (pitch.HasValue)
            {
                VarAudio.pitch = pitch.Value;
            }
            else if (useRandomPitch)
            {
                var randPitch = Random.Range(randomPitchMin, randomPitchMax);

                switch (randomPitchMode)
                {
                case RandomPitchMode.AddToClipPitch:
                    randPitch += OriginalPitch;
                    break;
                }

                VarAudio.pitch = randPitch;
            }
            else
            {
                // non random pitch
                VarAudio.pitch = OriginalPitch;
            }

            // in case it was changed at runtime.
            SetSpatialBlend();

            // set fade mode
            curFadeMode      = FadeMode.None;
            curPitchMode     = PitchMode.None;
            curDetectEndMode = DetectEndMode.DetectEnd;
            _maxVol          = maxVolume;
            if (maxCustomLoops == minCustomLoops)
            {
                _maxLoops = minCustomLoops;
            }
            else
            {
                _maxLoops = Random.Range(minCustomLoops, maxCustomLoops + 1);
            }

            LoadStatus = MasterAudio.VariationLoadStatus.Loading;

            switch (audLocation)
            {
            case MasterAudio.AudioLocation.Clip:
                FinishSetupToPlay();
                return;

            case MasterAudio.AudioLocation.ResourceFile:
                if (_loadResourceFileCoroutine != null)
                {
                    StopCoroutine(_loadResourceFileCoroutine);
                }

                _loadResourceFileCoroutine = StartCoroutine(AudioResourceOptimizer.PopulateSourcesWithResourceClipAsync(ResFileName, this,
                                                                                                                        FinishSetupToPlay, ResourceFailedToLoad));
                return;

#if ADDRESSABLES_ENABLED
            case MasterAudio.AudioLocation.Addressable:
                if (_loadAddressableCoroutine != null)
                {
                    StopCoroutine(_loadAddressableCoroutine);
                }

                _loadAddressableCoroutine = StartCoroutine(AudioAddressableOptimizer.PopulateSourceWithAddressableClipAsync(audioClipAddressable,
                                                                                                                            this, ParentGroup.AddressableUnusedSecondsLifespan, FinishSetupToPlay, ResourceFailedToLoad));
                return;
#endif
            }
        }
        /*! \endcond */

        #region Monobehavior events

        // ReSharper disable once UnusedMember.Local
        private void Awake() {
            useGUILayout = false;

            if (ControllerIsReady) {
                // already called by lazy load.
                return;
            }

            ControllerIsReady = false;

            // check for "extra" Playlist Controllers of the same name.
            // ReSharper disable once ArrangeStaticMemberQualifier
            var controllers = (PlaylistController[])GameObject.FindObjectsOfType(typeof(PlaylistController));
            var sameNameCount = 0;

            // ReSharper disable once ForCanBeConvertedToForeach
            for (var i = 0; i < controllers.Length; i++) {
                if (controllers[i].ControllerName == ControllerName) {
                    sameNameCount++;
                }
            }

            if (sameNameCount > 1) {
                Destroy(gameObject);
                Debug.Log(
                    "More than one Playlist Controller prefab exists in this Scene with the same name. Destroying the one called '" +
                    ControllerName + "'. You may wish to set up a Bootstrapper Scene so this does not occur.");
                return;
            }
            // end check

            _duckingMode = AudioDuckingMode.NotDucking;
            _currentSong = null;
            _songsPlayedFromPlaylist = 0;

            var audios = GetComponents<AudioSource>();
            if (audios.Length < 2) {
                Debug.LogError("This prefab should have exactly two Audio Source components. Please revert it.");
                return;
            }

            var ma = MasterAudio.SafeInstance;
            _willPersist = ma != null && ma.persistBetweenScenes;

            _audio1 = audios[0];
            _audio2 = audios[1];

            _audio1.clip = null;
            _audio2.clip = null;

            if (_audio1.playOnAwake || _audio2.playOnAwake) {
                Debug.LogWarning(
                    "One or more 'Play on Awake' checkboxes in the Audio Sources on Playlist Controller '" + name +
                    "' are checked. These are not used in Master Audio. Make sure to uncheck them before hitting Play next time. For Playlist Controllers, use the similarly named checkbox 'Start Playlist on Awake' in the Playlist Controller's Inspector.");
            }

            _activeAudio = _audio1;
            _transitioningAudio = _audio2;

#if UNITY_5
            _audio1.outputAudioMixerGroup = mixerChannel;
            _audio2.outputAudioMixerGroup = mixerChannel;

            SetSpatialBlend();
#endif

            _curFadeMode = FadeMode.None;
            _fadeCompleteCallback = null;
            _lostFocus = false;
        }
예제 #33
0
파일: Cue.cs 프로젝트: sethbattin/FNA
 internal void INTERNAL_startFadeIn(ushort ms)
 {
     // start is not used, since it's always 0 anyway -flibit
     INTERNAL_fadeEnd  = ms;
     INTERNAL_fadeMode = FadeMode.FadeIn;
 }
        private void CoUpdate() {
			if (MasterAudio.SafeInstance == null) {
				// abort, there's no MA game object.
				return;
			}

			// fix scheduled track play time if it has changed (it changes constantly).
            if (CanSchedule && !CurrentPlaylistSource.loop) {
                if (_scheduledSongsByAudioSource.Count > 0 && _scheduledSongsByAudioSource.ContainsKey(_audioClip)) {
                    var newStartTime = CalculateNextTrackStartTime();
                    var existingStartTime = _scheduledSongsByAudioSource[_audioClip];

                    if (Math.Abs(newStartTime - existingStartTime) > ScheduledSongMinBadOffset) {
                        Debug.LogWarning("Already Scheduled song '" + _audioClip.clip.name + "' was projected to be off its original scheduled time by over " + ScheduledSongMinBadOffset + " second(s) and has been rescheduled as accurately as possible. You probably changed the pitch of the song and/or its position. This can result in not perfect gapless playing.");
                        _audioClip.Stop(); // stop the previous scheduled play
                        ScheduleClipPlay(newStartTime);
                    }
                }
            }

            // gradual fade code
            if (_curFadeMode != FadeMode.GradualFade) {
                return;
            }

            if (_activeAudio == null) {
                return; // paused or error in setup
            }

            var newVolume = _playlistVolume + _slowFadeVolStep;

            // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
            if (_slowFadeVolStep > 0f) {
                newVolume = Math.Min(newVolume, _slowFadeTargetVolume);
            } else {
                newVolume = Math.Max(newVolume, _slowFadeTargetVolume);
            }

            _playlistVolume = newVolume;

            UpdateMasterVolume();

            // ReSharper disable once CompareOfFloatsByEqualityOperator
            if (newVolume != _slowFadeTargetVolume) {
                return;
            }
            if (MasterAudio.Instance.stopZeroVolumePlaylists && _slowFadeTargetVolume == 0f) {
                StopPlaylist();
            }

            if (_fadeCompleteCallback != null) {
                _fadeCompleteCallback();
                _fadeCompleteCallback = null;
            }
            _curFadeMode = FadeMode.None;
            // ReSharper disable once FunctionNeverReturns
        }
예제 #35
0
    /// <summary>
    /// This method allows you to fade the Playlist to a specified volume over X seconds.
    /// </summary>
    /// <param name="targetVolume">The volume to fade to.</param>
    /// <param name="fadeTime">The amount of time to fully fade to the target volume.</param>
    public void FadeToVolume(float targetVolume, float fadeTime, System.Action callback = null)
    {
        if (fadeTime <= MasterAudio.INNER_LOOP_CHECK_INTERVAL)
        {
            playlistVolume = targetVolume;
            UpdateMasterVolume();
            return;
        }

        curFadeMode = FadeMode.GradualFade;
        slowFadeTargetVolume = targetVolume;
        slowFadeVolStep = (slowFadeTargetVolume - playlistVolume) / (fadeTime / MasterAudio.INNER_LOOP_CHECK_INTERVAL);

        fadeCompleteCallback = callback;
    }
        /// <summary>
        /// This method allows you to fade the Playlist to a specified volume over X seconds.
        /// </summary>
        /// <param name="targetVolume">The volume to fade to.</param>
        /// <param name="fadeTime">The amount of time to fully fade to the target volume.</param>
        /// <param name="callback">Optional callback method</param>
        // ReSharper disable once RedundantNameQualifier
        public void FadeToVolume(float targetVolume, float fadeTime, System.Action callback = null) {
            if (!ControllerIsReady) {
                Debug.LogError(NotReadyMessage);
                return;
            }

            if (fadeTime <= MasterAudio.InnerLoopCheckInterval) {
                _playlistVolume = targetVolume;
                UpdateMasterVolume();
                _curFadeMode = FadeMode.None; // in case another fade is happening, stop it!
                return;
            }

            _curFadeMode = FadeMode.GradualFade;
            _slowFadeTargetVolume = targetVolume;
            _slowFadeVolStep = (_slowFadeTargetVolume - _playlistVolume) / (fadeTime / AudioUtil.FrameTime);

            _fadeCompleteCallback = callback;
        }
예제 #37
0
    IEnumerator CoUpdate()
    {
        while (true)
        {
            yield return StartCoroutine(CoroutineHelper.WaitForRealSeconds(MasterAudio.INNER_LOOP_CHECK_INTERVAL)); // works with zero timescale also.
            //yield return MasterAudio.loopDelay; // Stops working with zero timescale.

            // gradual fade code
            if (curFadeMode != FadeMode.GradualFade)
            {
                continue;
            }

            if (activeAudio == null)
            {
                continue; // paused or error in setup
            }

            var newVolume = playlistVolume + slowFadeVolStep;

            if (slowFadeVolStep > 0f)
            {
                newVolume = Math.Min(newVolume, slowFadeTargetVolume);
            }
            else
            {
                newVolume = Math.Max(newVolume, slowFadeTargetVolume);
            }

            playlistVolume = newVolume;

            UpdateMasterVolume();

            if (newVolume == slowFadeTargetVolume)
            {
                if (fadeCompleteCallback != null)
                {
                    fadeCompleteCallback();
                    fadeCompleteCallback = null;
                }
                curFadeMode = FadeMode.None;
            }
        }
    }
        public double OpacityValueStart(FadeMode fadeMode)
        {
            FadeAnimator animator = new FadeAnimator(fadeMode);

            return(animator.CurrentOpacity);
        }
예제 #39
0
 public FadeAnimator(FadeMode fadeMode)
 {
     this.FadeMode              = fadeMode;
     this.CurrentOpacity        = fadeMode == FadeMode.FadeIn ? 0 : 1;
     this.OpacityDeltaPerSecond = 1;
 }
예제 #40
0
 public void FadeInOut()
 {
     this.enabled   = true;
     this._inout    = true;
     this._fadeMode = FadeMode.FadeToBlack;
 }
예제 #41
0
    public void Play(float? pitch, float maxVolume, string gameObjectName, float volPercent, float targetVol, float? targetPitch, Transform sourceTrans, bool attach, float delayTime, bool isChaining, bool isSingleSubscribedPlay)
    {
        SoundFinished = null; // clear it out so subscribers don't have to clean up
        isWaitingForDelay = false;

        playSndParam.soundType = gameObjectName;
        playSndParam.volumePercentage = volPercent;
        playSndParam.groupCalcVolume = targetVol;
        playSndParam.pitch = targetPitch;
        playSndParam.sourceTrans = sourceTrans;
        playSndParam.attachToSource = attach;
        playSndParam.delaySoundTime = delayTime;
        playSndParam.isChainLoop = isChaining;
        playSndParam.isSingleSubscribedPlay = isSingleSubscribedPlay;
        playSndParam.isPlaying = true;

        if (MasterAudio.HasAsyncResourceLoaderFeature() && ShouldLoadAsync) {
            StopAllCoroutines(); // The only Coroutine right now requires pro version and Unity 4.5.3
        }

        // compute pitch
        if (pitch.HasValue) {
            VarAudio.pitch = pitch.Value;
        } else if (useRandomPitch) {
            var randPitch = UnityEngine.Random.Range(randomPitchMin, randomPitchMax);

            switch (randomPitchMode) {
                case RandomPitchMode.AddToClipPitch:
                    randPitch += OriginalPitch;
                    break;
            }

            VarAudio.pitch = randPitch;
        } else { // non random pitch
            VarAudio.pitch = OriginalPitch;
        }

        // set fade mode
        this.curFadeMode = FadeMode.None;
        curDetectEndMode = DetectEndMode.DetectEnd;
        _maxVol = maxVolume;

        if (audLocation == MasterAudio.AudioLocation.Clip) {
            FinishSetupToPlay();
            return;
        }

        if (MasterAudio.HasAsyncResourceLoaderFeature() && ShouldLoadAsync) {
            StartCoroutine(AudioResourceOptimizer.PopulateSourcesWithResourceClipAsync(ResFileName, this, FinishSetupToPlay, ResourceFailedToLoad));
        } else {
            if (!AudioResourceOptimizer.PopulateSourcesWithResourceClip(ResFileName, this)) {
                return; // audio file not found!
            }

            FinishSetupToPlay();
        }
    }
예제 #42
0
 public void FadeToBlack()
 {
     this.enabled   = true;
     this._fadeMode = FadeMode.FadeToBlack;
 }
예제 #43
0
    /// <summary>
    /// This method allows you to pause the audio being played by this Variation. This is automatically called by MasterAudio.PauseSoundGroup and MasterAudio.PauseBus.
    /// </summary>
    public void Pause()
    {
        if (audLocation == MasterAudio.AudioLocation.ResourceFile && !MasterAudio.Instance.resourceClipsPauseDoNotUnload)
        {
            Stop();
            return;
        }

        VarAudio.Pause();
        this.curFadeMode = FadeMode.None;
		this.curDetectEndMode = DetectEndMode.None; // necessary so that the clip can be unpaused.
		
        MaybeUnloadClip();
    }
예제 #44
0
 public void FadeToClear()
 {
     this._fadeMode = FadeMode.FadeToClear;
 }
예제 #45
0
    private IEnumerator FadeOverTimeToVolume(float targetVolume, float fadeTime)
    {
        if (fadeTime <= MasterAudio.INNER_LOOP_CHECK_INTERVAL)
        {
            VarAudio.volume = targetVolume; // time really short, just do it at once.
            if (VarAudio.volume <= 0f)
            {
                Stop();
            }
            curFadeMode = FadeMode.None;
            yield break;
        }
		
		// wait for clip to start playing.
		if (MasterAudio.IgnoreTimeScale) { 
			yield return StartCoroutine(CoroutineHelper.WaitForActualSeconds(MasterAudio.INNER_LOOP_CHECK_INTERVAL));
		} else {
			yield return MasterAudio.InnerLoopDelay;
		}

        var volStep = (targetVolume - VarAudio.volume) / (fadeTime / MasterAudio.INNER_LOOP_CHECK_INTERVAL);
        float newVol;
        while (VarAudio.volume != targetVolume && curFadeMode == FadeMode.GradualFade)
        {
            newVol = VarAudio.volume + volStep;

            if (volStep > 0f)
            {
                newVol = Math.Min(newVol, targetVolume);
            }
            else
            {
                newVol = Math.Max(newVol, targetVolume);
            }

            VarAudio.volume = newVol;

			// wait for clip to start playing.
			if (MasterAudio.IgnoreTimeScale) { 
				yield return StartCoroutine(CoroutineHelper.WaitForActualSeconds(MasterAudio.INNER_LOOP_CHECK_INTERVAL));
			} else {
				yield return MasterAudio.InnerLoopDelay;
			}
        }

        if (VarAudio.volume <= 0f)
        {
            Stop();
        }

        if (curFadeMode != FadeMode.GradualFade)
        {
            yield break; // in case another fade cancelled this one
        }

        curFadeMode = FadeMode.None;
    }
예제 #46
0
        /*! \cond PRIVATE */
        public void Play(float?pitch, float maxVolume, string gameObjectName, float volPercent, float targetVol,
                         float?targetPitch, Transform sourceTrans, bool attach, float delayTime, bool isChaining,
                         bool isSingleSubscribedPlay)
        {
            if (!MasterAudio.IsWarming && audLocation == MasterAudio.AudioLocation.FileOnInternet)
            {
                switch (internetFileLoadStatus)
                {
                case MasterAudio.InternetFileLoadStatus.Loading:
                    if (MasterAudio.Instance.LogSounds)
                    {
                        MasterAudio.LogWarning("Cannot play Variation '" + name +
                                               "' because its Internet file has not been downloaded yet.");
                    }
                    return;

                case MasterAudio.InternetFileLoadStatus.Failed:
                    if (MasterAudio.Instance.LogSounds)
                    {
                        MasterAudio.LogWarning("Cannot play Variation '" + name +
                                               "' because its Internet file failed downloading.");
                    }
                    return;
                }
            }

            SoundFinished      = null; // clear it out so subscribers don't have to clean up
            _isWaitingForDelay = false;

            _playSndParam.SoundType        = gameObjectName;
            _playSndParam.VolumePercentage = volPercent;
            _playSndParam.GroupCalcVolume  = targetVol;
            _playSndParam.Pitch            = targetPitch;
            _playSndParam.SourceTrans      = sourceTrans;
            _playSndParam.AttachToSource   = attach;
            _playSndParam.DelaySoundTime   = delayTime;
            _playSndParam.IsChainLoop      = isChaining ||
                                             ParentGroup.curVariationMode == MasterAudioGroup.VariationMode.LoopedChain;
            _playSndParam.IsSingleSubscribedPlay = isSingleSubscribedPlay;
            _playSndParam.IsPlaying = true;

            SetPriority(); // reset it back to normal priority in case you're playing 2D this time.

            if (MasterAudio.HasAsyncResourceLoaderFeature() && ShouldLoadAsync)
            {
                StopAllCoroutines(); // The only Coroutine right now requires pro version and Unity 4.5.3
            }

            // compute pitch
            if (pitch.HasValue)
            {
                VarAudio.pitch = pitch.Value;
            }
            else if (useRandomPitch)
            {
                var randPitch = Random.Range(randomPitchMin, randomPitchMax);

                switch (randomPitchMode)
                {
                case RandomPitchMode.AddToClipPitch:
                    randPitch += OriginalPitch;
                    break;
                }

                VarAudio.pitch = randPitch;
            }
            else
            {
                // non random pitch
                VarAudio.pitch = OriginalPitch;
            }

            // set fade mode
            curFadeMode      = FadeMode.None;
            curDetectEndMode = DetectEndMode.DetectEnd;
            _maxVol          = maxVolume;

            switch (audLocation)
            {
            case MasterAudio.AudioLocation.Clip:
                FinishSetupToPlay();
                return;

            case MasterAudio.AudioLocation.ResourceFile:
                if (MasterAudio.HasAsyncResourceLoaderFeature() && ShouldLoadAsync)
                {
                    StartCoroutine(AudioResourceOptimizer.PopulateSourcesWithResourceClipAsync(ResFileName, this,
                                                                                               FinishSetupToPlay, ResourceFailedToLoad));
                }
                else
                {
                    if (!AudioResourceOptimizer.PopulateSourcesWithResourceClip(ResFileName, this))
                    {
                        return;     // audio file not found!
                    }

                    FinishSetupToPlay();
                }
                return;

            case MasterAudio.AudioLocation.FileOnInternet:
                FinishSetupToPlay();
                return;
            }
        }
예제 #47
0
    private IEnumerator FadeInOut()
    {
        var fadeOutStartTime = VarAudio.clip.length - (fadeOutTime * VarAudio.pitch);

		// wait for clip to start playing
		if (MasterAudio.IgnoreTimeScale) { 
			yield return StartCoroutine(CoroutineHelper.WaitForActualSeconds(MasterAudio.INNER_LOOP_CHECK_INTERVAL));
		} else {
			yield return MasterAudio.InnerLoopDelay;
		}

        var stepVolumeUp = fadeMaxVolume / fadeInTime * MasterAudio.INNER_LOOP_CHECK_INTERVAL;

        curFadeMode = FadeMode.FadeInOut; // wait to set this so it stops the previous one if it's still going.

        if (fadeInTime > 0f)
        {
            while (VarAudio.isPlaying && curFadeMode == FadeMode.FadeInOut && VarAudio.time < fadeInTime)
            {
                VarAudio.volume += stepVolumeUp;

				if (MasterAudio.IgnoreTimeScale) { 
					yield return StartCoroutine(CoroutineHelper.WaitForActualSeconds(MasterAudio.INNER_LOOP_CHECK_INTERVAL));
				} else {
					yield return MasterAudio.InnerLoopDelay;
				}
            }
        }

        if (curFadeMode != FadeMode.FadeInOut)
        {
            yield break; // in case another fade cancelled this one
        }

        VarAudio.volume = fadeMaxVolume; // just in case it didn't align exactly

        if (fadeOutTime == 0f || VarAudio.loop)
        {
            yield break; // nothing more to do!
        }

        // wait for fade out time.
        while (VarAudio.isPlaying && curFadeMode == FadeMode.FadeInOut && VarAudio.time < fadeOutStartTime)
        {
			if (MasterAudio.IgnoreTimeScale) { 
				yield return StartCoroutine(CoroutineHelper.WaitForActualSeconds(MasterAudio.INNER_LOOP_CHECK_INTERVAL));
			} else {
				yield return MasterAudio.InnerLoopDelay;
			}
        }

        if (curFadeMode != FadeMode.FadeInOut)
        {
            yield break; // in case another fade cancelled this one
        }

        var stepVolumeDown = fadeMaxVolume / fadeOutTime * MasterAudio.INNER_LOOP_CHECK_INTERVAL;

        while (VarAudio.isPlaying && curFadeMode == FadeMode.FadeInOut && VarAudio.volume > 0)
        {
            VarAudio.volume -= stepVolumeDown;
			if (MasterAudio.IgnoreTimeScale) { 
				yield return StartCoroutine(CoroutineHelper.WaitForActualSeconds(MasterAudio.INNER_LOOP_CHECK_INTERVAL));
			} else {
				yield return MasterAudio.InnerLoopDelay;
			}
        }

        GetComponent<AudioSource>().volume = 0f;
        Stop();

        if (curFadeMode != FadeMode.FadeInOut)
        {
            yield break; // in case another fade cancelled this one
        }

        curFadeMode = FadeMode.None;
    }
예제 #48
0
        internal bool INTERNAL_update()
        {
            // If we're not running, save some instructions...
            if (!INTERNAL_timer.IsRunning)
            {
                return(true);
            }
            elapsedFrames += 1;

            // User control updates
            if (INTERNAL_data.IsUserControlled)
            {
                string varName = INTERNAL_data.UserControlVariable;
                if (INTERNAL_userControlledPlaying &&
                    (INTERNAL_baseEngine.INTERNAL_isGlobalVariable(varName) ?
                     !MathHelper.WithinEpsilon(INTERNAL_controlledValue, INTERNAL_baseEngine.GetGlobalVariable(varName)) :
                     !MathHelper.WithinEpsilon(INTERNAL_controlledValue, GetVariable(INTERNAL_data.UserControlVariable))))
                {
                    // TODO: Crossfading
                    foreach (SoundEffectInstance sfi in INTERNAL_instancePool)
                    {
                        sfi.Stop();
                        sfi.Dispose();
                    }
                    INTERNAL_instancePool.Clear();
                    INTERNAL_instanceVolumes.Clear();
                    INTERNAL_instancePitches.Clear();
                    INTERNAL_rpcTrackVolumes.Clear();
                    INTERNAL_rpcTrackPitches.Clear();
                    if (!INTERNAL_calculateNextSound())
                    {
                        // Nothing to play, bail.
                        return(true);
                    }
                    INTERNAL_activeSound.InitializeClips();
                    INTERNAL_timer.Stop();
                    INTERNAL_timer.Reset();
                    INTERNAL_timer.Start();
                }

                if (INTERNAL_activeSound == null)
                {
                    return(INTERNAL_userControlledPlaying);
                }
            }

            // Trigger events for each track
            foreach (XACTClipInstance clip in INTERNAL_activeSound.Clips)
            {
                // Play events when the timestamp has been hit.
                for (int i = 0; i < clip.Events.Count; i += 1)
                {
                    EventInstance evt = clip.Events[i];

                    if (!evt.Played &&
                        INTERNAL_timer.ElapsedMilliseconds > evt.Timestamp)
                    {
                        evt.Apply(
                            this,
                            null,
                            INTERNAL_timer.ElapsedMilliseconds / 1000.0f
                            );
                    }
                }
            }


            // Clear out sound effect instances as they finish
            for (int i = 0; i < INTERNAL_instancePool.Count; i += 1)
            {
                if (INTERNAL_instancePool[i].State == SoundState.Stopped)
                {
                    // Get the event that spawned this instance...
                    PlayWaveEventInstance evtInstance =
                        INTERNAL_playWaveEventBySound[INTERNAL_instancePool[i]];
                    double prevVolume = INTERNAL_instanceVolumes[i];
                    short  prevPitch  = INTERNAL_instancePitches[i];

                    // Then delete all the guff
                    INTERNAL_playWaveEventBySound.Remove(INTERNAL_instancePool[i]);
                    INTERNAL_instancePool[i].Dispose();
                    INTERNAL_instancePool.RemoveAt(i);
                    INTERNAL_instanceVolumes.RemoveAt(i);
                    INTERNAL_instancePitches.RemoveAt(i);
                    INTERNAL_rpcTrackVolumes.RemoveAt(i);
                    INTERNAL_rpcTrackPitches.RemoveAt(i);

                    // Increment the loop counter, try to get another loop
                    evtInstance.LoopCount += 1;
                    PlayWave(evtInstance, prevVolume, prevPitch);

                    // Removed a wave, have to step back...
                    i -= 1;
                }
            }

            // Fade in/out
            float fadePerc = 1.0f;

            if (INTERNAL_fadeMode != FadeMode.None)
            {
                if (INTERNAL_fadeMode == FadeMode.FadeOut)
                {
                    if (INTERNAL_category.crossfadeType == CrossfadeType.Linear)
                    {
                        fadePerc = (
                            INTERNAL_fadeEnd -
                            (
                                INTERNAL_timer.ElapsedMilliseconds -
                                INTERNAL_fadeStart
                            )
                            ) / (float)INTERNAL_fadeEnd;
                    }
                    else
                    {
                        throw new NotImplementedException("Unhandled CrossfadeType!");
                    }
                    if (fadePerc <= 0.0f)
                    {
                        Stop(AudioStopOptions.Immediate);
                        INTERNAL_fadeMode = FadeMode.None;
                        return(false);
                    }
                }
                else if (INTERNAL_fadeMode == FadeMode.FadeIn)
                {
                    if (INTERNAL_category.crossfadeType == CrossfadeType.Linear)
                    {
                        fadePerc = INTERNAL_timer.ElapsedMilliseconds / (float)INTERNAL_fadeEnd;
                    }
                    else
                    {
                        throw new NotImplementedException("Unhandled CrossfadeType!");
                    }
                    if (fadePerc > 1.0f)
                    {
                        fadePerc          = 1.0f;
                        INTERNAL_fadeMode = FadeMode.None;
                    }
                }
                else if (INTERNAL_fadeMode == FadeMode.ReleaseRpc)
                {
                    float releasePerc = (
                        INTERNAL_timer.ElapsedMilliseconds -
                        INTERNAL_fadeStart
                        ) / (float)INTERNAL_maxRpcReleaseTime;
                    if (releasePerc > 1.0f)
                    {
                        Stop(AudioStopOptions.Immediate);
                        INTERNAL_fadeMode = FadeMode.None;
                        return(false);
                    }
                }
                else
                {
                    throw new NotImplementedException("Unsupported FadeMode!");
                }
            }

            // If everything has been played and finished, we're done here.
            if (INTERNAL_instancePool.Count == 0)
            {
                bool allPlayed = true;
                foreach (XACTClipInstance clipInstance in INTERNAL_activeSound.Clips)
                {
                    foreach (EventInstance evt in clipInstance.Events)
                    {
                        if (!evt.Played)
                        {
                            allPlayed = false;
                            break;
                        }
                    }
                }
                if (allPlayed)
                {
                    // If this is managed, we're done completely.
                    if (INTERNAL_isManaged)
                    {
                        Dispose();
                    }
                    else
                    {
                        KillCue();
                    }
                    if (INTERNAL_userControlledPlaying)
                    {
                        // We're "still" "playing" right now...
                        return(true);
                    }
                    IsStopped = true;
                    return(false);
                }
            }

            // RPC updates
            float rpcVolume = 0.0f;
            float rpcPitch  = 0.0f;
            float hfGain    = 1.0f;
            float lfGain    = 1.0f;

            for (int i = 0; i < INTERNAL_activeSound.Sound.RPCCodes.Count; i += 1)
            {
                // Are we processing an RPC targeting the sound itself rather than a track?
                bool isSoundRpc = i == 0 && INTERNAL_activeSound.Sound.HasSoundRpcs;

                // If there is an RPC targeting the sound instance itself, it is handled in rpcVolume/rpcPitch, and the first track is at i-1.
                int trackRpcIndex = INTERNAL_activeSound.Sound.HasSoundRpcs ? i - 1 : i;

                // If this RPC Code is for a track that is not active yet, we have nothing to do.
                if (trackRpcIndex >= INTERNAL_instancePool.Count)
                {
                    // FIXME: This presumes that tracks start in order, which doesn't have to be true.
                    break;
                }
                if (!isSoundRpc)
                {
                    INTERNAL_rpcTrackVolumes[trackRpcIndex] = 0.0f;
                    INTERNAL_rpcTrackPitches[trackRpcIndex] = 0.0f;
                }

                foreach (uint curCode in INTERNAL_activeSound.Sound.RPCCodes[i])
                {
                    RPC   curRPC = INTERNAL_baseEngine.INTERNAL_getRPC(curCode);
                    float result;
                    if (!INTERNAL_baseEngine.INTERNAL_isGlobalVariable(curRPC.Variable))
                    {
                        float variableValue;

                        if (curRPC.Variable.Equals("AttackTime"))
                        {
                            PlayWaveEvent playWaveEvent =
                                (PlayWaveEvent)INTERNAL_activeSound.Sound.INTERNAL_clips[trackRpcIndex].Events[0];

                            long elapsedFromPlay = INTERNAL_timer.ElapsedMilliseconds
                                                   - playWaveEvent.Timestamp;
                            variableValue = elapsedFromPlay;
                        }
                        else if (curRPC.Variable.Equals("ReleaseTime"))
                        {
                            if (INTERNAL_fadeMode == FadeMode.ReleaseRpc)
                            {
                                long elapsedFromStop = INTERNAL_timer.ElapsedMilliseconds - INTERNAL_fadeStart;
                                variableValue = elapsedFromStop;
                            }
                            else
                            {
                                variableValue = 0.0f;
                            }
                        }
                        else
                        {
                            variableValue = GetVariable(curRPC.Variable);
                        }

                        result = curRPC.CalculateRPC(variableValue);
                    }
                    else
                    {
                        // It's a global variable we're looking for!
                        result = curRPC.CalculateRPC(
                            INTERNAL_baseEngine.GetGlobalVariable(
                                curRPC.Variable
                                )
                            );
                    }
                    if (curRPC.Parameter == RPCParameter.Volume)
                    {
                        // If this RPC targets the sound instance itself then apply to the dedicated variable.
                        if (isSoundRpc)
                        {
                            rpcVolume += result;
                        }
                        else
                        {
                            INTERNAL_rpcTrackVolumes[trackRpcIndex] += result;
                        }
                    }
                    else if (curRPC.Parameter == RPCParameter.Pitch)
                    {
                        float pitch = result;
                        if (isSoundRpc)
                        {
                            rpcPitch += pitch;
                        }
                        else
                        {
                            INTERNAL_rpcTrackPitches[trackRpcIndex] += pitch;
                        }
                    }
                    else if (curRPC.Parameter == RPCParameter.FilterFrequency)
                    {
                        // FIXME: Just listening to the last RPC!
                        float hf = result / 20000.0f;
                        float lf = 1.0f - hf;
                        if (isSoundRpc)
                        {
                            hfGain = hf;
                            lfGain = lf;
                        }
                        else
                        {
                            throw new NotImplementedException("Per-track filter RPCs!");
                        }
                    }
                    else
                    {
                        throw new NotImplementedException(
                                  "RPC Parameter Type: " + curRPC.Parameter.ToString()
                                  );
                    }
                }
            }

            // Sound effect instance updates
            for (int i = 0; i < INTERNAL_instancePool.Count; i += 1)
            {
                /* The final volume should be the combination of the
                 * authored volume, category volume, RPC sound/track
                 * volumes, event volumes, and fade.
                 */
                INTERNAL_instancePool[i].Volume = XACTCalculator.CalculateAmplitudeRatio(
                    INTERNAL_instanceVolumes[i] +
                    rpcVolume +
                    INTERNAL_rpcTrackVolumes[i] +
                    eventVolume
                    ) * INTERNAL_category.INTERNAL_volume.Value * fadePerc;

                /* The final pitch should be the combination of the
                 * authored pitch, RPC sound/track pitches, and event
                 * pitch.
                 *
                 * XACT uses -1200 to 1200 (+/- 12 semitones),
                 * XNA uses -1.0f to 1.0f (+/- 1 octave).
                 */
                INTERNAL_instancePool[i].Pitch = (
                    INTERNAL_instancePitches[i] +
                    rpcPitch +
                    INTERNAL_rpcTrackPitches[i] +
                    eventPitch
                    ) / 1200.0f;

                /* The final filter is determined by the instance's filter type,
                 * in addition to our calculation of the HF/LF gain values.
                 */
                byte fType = INTERNAL_instancePool[i].FilterType;
                if (fType == 0xFF)
                {
                    // No-op, no filter!
                }
                else if (fType == 0)
                {
                    INTERNAL_instancePool[i].INTERNAL_applyLowPassFilter(hfGain);
                }
                else if (fType == 1)
                {
                    INTERNAL_instancePool[i].INTERNAL_applyHighPassFilter(lfGain);
                }
                else if (fType == 2)
                {
                    INTERNAL_instancePool[i].INTERNAL_applyBandPassFilter(hfGain, lfGain);
                }
                else
                {
                    throw new InvalidOperationException("Unhandled filter type!");
                }

                // Update 3D position, if applicable
                if (INTERNAL_isPositional)
                {
                    INTERNAL_instancePool[i].Apply3D(
                        INTERNAL_listener,
                        INTERNAL_emitter
                        );
                }
            }

            return(true);
        }
예제 #49
0
 /// <summary>
 /// Hide the indicator with a fade out animation
 /// </summary>
 public void Deactivate()
 {
     currentFadeMode = FadeMode.FadeOut;
     fadeStartTime   = Time.time;
 }
예제 #50
0
 internal void INTERNAL_startReleaseRpc(ushort ms)
 {
     INTERNAL_fadeStart = INTERNAL_timer.ElapsedMilliseconds;
     INTERNAL_fadeEnd   = ms;
     INTERNAL_fadeMode  = FadeMode.ReleaseRpc;
 }
예제 #51
0
 /// <summary>
 /// Starts fading in the `state` over the course of the `fadeDuration` while fading out all others in the same
 /// layer. Returns the `state`.
 /// <para></para>
 /// If the `state` was already playing and fading in with less time remaining than the `fadeDuration`, this
 /// method will allow it to complete the existing fade rather than starting a slower one.
 /// <para></para>
 /// If the layer currently has 0 <see cref="AnimancerNode.Weight"/>, this method will fade in the layer itself
 /// and simply <see cref="AnimancerState.Play(AnimancerState)"/> the `state`.
 /// <para></para>
 /// Animancer Lite only allows the default `fadeDuration` (0.25 seconds) in a runtime build.
 /// </summary>
 public AnimancerState Play(AnimancerState state, float fadeDuration, FadeMode mode = FadeMode.FixedSpeed)
 {
     return(Playable.Play(state, fadeDuration, mode));
 }
예제 #52
0
    private void OnPlayBGMWithFade(SoundClip bgSoundClip, SoundClipPools.SoundClipParam param, bool reset)
    {
        if (mBGAudioSource != null && bgSoundClip != null)
        {
            mLastMusicID = param.m_clipID;
            if (mBGAudioSource.m_AudioSource.isPlaying) //正常播放上一首背景音乐
            {
                if (mNextSoundClip != null && mNextSoundClip.mUID == bgSoundClip.mUID)
                {
                    return;
                }
                mFadeOutTime  = param.m_fadeOutTime;
                mFadeInTime   = param.m_fadeInTime;
                mFadeOutTimer = 0;
                mFadeInTimer  = 0;
                if (mFadeOutTime <= 0)
                {
                    //force Remove clip from pool, special for bgmusic
                    var deluid = mBGAudioSource.m_uID;
                    SetAudioSource(mBGAudioSource, bgSoundClip, 1.0f);
                    mSoundClipPools.ForceRemoveClipByID(deluid);

                    mCurBGVolume = bgSoundClip.mVolume;
                    if (mFadeInTime <= 0)
                    {
                        mBGAudioSource.m_AudioSource.Play();
                        mFadeMode = FadeMode.None;
                    }
                    else
                    {
                        mBGAudioSource.m_AudioSource.volume = 0;
                        mBGAudioSource.m_AudioSource.Play();
                        mFadeMode = FadeMode.FadeIn;
                    }
                }
                else
                {
                    mNextSoundClip = bgSoundClip;
                    mFadeMode      = FadeMode.FadeOut;
                }
            }
            else //没在播放,直接播放
            {
                mFadeInTime  = param.m_fadeInTime;
                mFadeInTimer = 0;

                //force Remove clip from pool, special for bgmusic
                var deluid = mBGAudioSource.m_uID;
                SetAudioSource(mBGAudioSource, bgSoundClip, 1.0f);
                mSoundClipPools.ForceRemoveClipByID(deluid);

                mCurBGVolume = bgSoundClip.mVolume;
                if (mFadeInTime <= 0)
                {
                    mBGAudioSource.m_AudioSource.Play();
                    mFadeMode = FadeMode.None;
                }
                else
                {
                    mBGAudioSource.m_AudioSource.volume = 0;
                    mBGAudioSource.m_AudioSource.Play();
                    mFadeMode = FadeMode.FadeIn;
                }
            }
        }
    }
예제 #53
0
 public void StartFade(FadeMode fadeMode, float fadeTimer)
 {
     StopCoroutine("Fade");
     StartCoroutine(Fade(fadeMode, fadeTimer));
 }
예제 #54
0
 public static void onlyFadeStart()
 {
     fadeMode = FadeMode.onlyFadeStart;
 }
예제 #55
0
파일: Cue.cs 프로젝트: clarvalon/FNA
		internal bool INTERNAL_update()
		{
			// If we're not running, save some instructions...
			if (!INTERNAL_timer.IsRunning)
			{
				return true;
			}

			// Play events when the timestamp has been hit.
			for (int i = 0; i < INTERNAL_eventList.Count; i += 1)
			{
				if (	!INTERNAL_eventPlayed[i] &&
					INTERNAL_timer.ElapsedMilliseconds > INTERNAL_eventList[i].Timestamp	)
				{
					uint type = INTERNAL_eventList[i].Type;
					if (type == 1)
					{
						PlayWave((PlayWaveEvent) INTERNAL_eventList[i]);
					}
					else if (type == 2)
					{
						eventVolume = ((SetVolumeEvent) INTERNAL_eventList[i]).GetVolume();
					}
					else if (type == 3)
					{
						eventPitch = ((SetPitchEvent) INTERNAL_eventList[i]).GetPitch();
					}
					else
					{
						throw new NotImplementedException("Unhandled XACTEvent type!");
					}
					INTERNAL_eventPlayed[i] = true;
				}
			}

			// Clear out sound effect instances as they finish
			for (int i = 0; i < INTERNAL_instancePool.Count; i += 1)
			{
				if (INTERNAL_instancePool[i].State == SoundState.Stopped)
				{
					// Get the event that spawned this instance...
					PlayWaveEvent evt = (PlayWaveEvent) INTERNAL_waveEventSounds[INTERNAL_instancePool[i]];

					// Then delete all the guff
					INTERNAL_waveEventSounds.Remove(INTERNAL_instancePool[i]);
					INTERNAL_instancePool[i].Dispose();
					INTERNAL_instancePool.RemoveAt(i);
					INTERNAL_instanceVolumes.RemoveAt(i);
					INTERNAL_instancePitches.RemoveAt(i);
					INTERNAL_rpcTrackVolumes.RemoveAt(i);
					INTERNAL_rpcTrackPitches.RemoveAt(i);

					// Increment the loop counter, try to get another loop
					INTERNAL_eventLoops[evt] += 1;
					PlayWave(evt);

					// Removed a wave, have to step back...
					i -= 1;
				}
			}

			// Fade in/out
			float fadePerc = 1.0f;
			if (INTERNAL_fadeMode != FadeMode.None)
			{
				if (INTERNAL_fadeMode == FadeMode.FadeOut)
				{
					if (INTERNAL_category.crossfadeType == CrossfadeType.Linear)
					{
						fadePerc = (INTERNAL_fadeEnd - (INTERNAL_timer.ElapsedMilliseconds - INTERNAL_fadeStart)) / (float) INTERNAL_fadeEnd;
					}
					else
					{
						throw new NotImplementedException("Unhandled CrossfadeType!");
					}
					if (fadePerc <= 0.0f)
					{
						Stop(AudioStopOptions.Immediate);
						INTERNAL_fadeMode = FadeMode.None;
						return false;
					}
				}
				else
				{
					if (INTERNAL_category.crossfadeType == CrossfadeType.Linear)
					{
						fadePerc = INTERNAL_timer.ElapsedMilliseconds / (float) INTERNAL_fadeEnd;
					}
					else
					{
						throw new NotImplementedException("Unhandled CrossfadeType!");
					}
					if (fadePerc > 1.0f)
					{
						fadePerc = 1.0f;
						INTERNAL_fadeMode = FadeMode.None;
					}
				}
			}

			// User control updates
			if (INTERNAL_data.IsUserControlled)
			{
				string varName = INTERNAL_data.UserControlVariable;
				if (	INTERNAL_userControlledPlaying &&
					(INTERNAL_baseEngine.INTERNAL_isGlobalVariable(varName) ?
						!MathHelper.WithinEpsilon(INTERNAL_controlledValue, INTERNAL_baseEngine.GetGlobalVariable(varName)) :
						!MathHelper.WithinEpsilon(INTERNAL_controlledValue, GetVariable(INTERNAL_data.UserControlVariable)))	)
				{
					// TODO: Crossfading
					foreach (SoundEffectInstance sfi in INTERNAL_instancePool)
					{
						sfi.Stop();
						sfi.Dispose();
					}
					INTERNAL_instancePool.Clear();
					INTERNAL_instanceVolumes.Clear();
					INTERNAL_instancePitches.Clear();
					INTERNAL_rpcTrackVolumes.Clear();
					INTERNAL_rpcTrackPitches.Clear();
					if (!INTERNAL_calculateNextSound())
					{
						// Nothing to play, bail.
						return true;
					}
					INTERNAL_activeSound.GatherEvents(INTERNAL_eventList);
					foreach (XACTEvent evt in INTERNAL_eventList)
					{
						INTERNAL_eventPlayed.Add(false);
						INTERNAL_eventLoops.Add(evt, 0);
					}
					INTERNAL_timer.Stop();
					INTERNAL_timer.Reset();
					INTERNAL_timer.Start();
				}

				if (INTERNAL_activeSound == null)
				{
					return INTERNAL_userControlledPlaying;
				}
			}

			// If everything has been played and finished, we're done here.
			if (INTERNAL_instancePool.Count == 0)
			{
				bool allPlayed = true;
				foreach (bool played in INTERNAL_eventPlayed)
				{
					if (!played)
					{
						allPlayed = false;
						break;
					}
				}
				if (allPlayed)
				{
					// If this is managed, we're done completely.
					if (INTERNAL_isManaged)
					{
						Dispose();
					}
					else
					{
						INTERNAL_timer.Stop();
						INTERNAL_timer.Reset();
						INTERNAL_category.INTERNAL_removeActiveCue(this);
					}
					return INTERNAL_userControlledPlaying;
				}
			}

			// RPC updates
			float rpcVolume = 1.0f;
			float rpcPitch = 0.0f;
			float hfGain = 1.0f;
			float lfGain = 1.0f;
			for (int i = 0; i < INTERNAL_activeSound.RPCCodes.Count; i += 1)
			{
				if (i > INTERNAL_instancePool.Count)
				{
					break;
				}
				if (i > 0)
				{
					INTERNAL_rpcTrackVolumes[i - 1] = 1.0f;
					INTERNAL_rpcTrackPitches[i - 1] = 0.0f;
				}
				foreach (uint curCode in INTERNAL_activeSound.RPCCodes[i])
				{
					RPC curRPC = INTERNAL_baseEngine.INTERNAL_getRPC(curCode);
					float result;
					if (!INTERNAL_baseEngine.INTERNAL_isGlobalVariable(curRPC.Variable))
					{
						result = curRPC.CalculateRPC(GetVariable(curRPC.Variable));
					}
					else
					{
						// It's a global variable we're looking for!
						result = curRPC.CalculateRPC(
							INTERNAL_baseEngine.GetGlobalVariable(
								curRPC.Variable
							)
						);
					}
					if (curRPC.Parameter == RPCParameter.Volume)
					{
						float vol = XACTCalculator.CalculateAmplitudeRatio(result / 100.0);
						if (i == 0)
						{
							rpcVolume *= vol;
						}
						else
						{
							INTERNAL_rpcTrackVolumes[i - 1] *= vol;
						}
					}
					else if (curRPC.Parameter == RPCParameter.Pitch)
					{
						float pitch = result / 1000.0f;
						if (i == 0)
						{
							rpcPitch += pitch;
						}
						else
						{
							INTERNAL_rpcTrackPitches[i - 1] += pitch;
						}
					}
					else if (curRPC.Parameter == RPCParameter.FilterFrequency)
					{
						// FIXME: Just listening to the last RPC!
						float hf = result / 20000.0f;
						float lf = 1.0f - hf;
						if (i == 0)
						{
							hfGain = hf;
							lfGain = lf;
						}
						else
						{
							throw new NotImplementedException("Per-track filter RPCs!");
						}
					}
					else
					{
						throw new NotImplementedException("RPC Parameter Type: " + curRPC.Parameter.ToString());
					}
				}
			}

			// Sound effect instance updates
			for (int i = 0; i < INTERNAL_instancePool.Count; i += 1)
			{
				/* The final volume should be the combination of the
				 * authored volume, category volume, RPC/Event volumes, and fade.
				 */
				INTERNAL_instancePool[i].Volume = (
					INTERNAL_instanceVolumes[i] *
					INTERNAL_category.INTERNAL_volume.Value *
					rpcVolume *
					INTERNAL_rpcTrackVolumes[i] *
					eventVolume *
					fadePerc
				);

				/* The final pitch should be the combination of the
				 * authored pitch and RPC/Event pitch results.
				 */
				INTERNAL_instancePool[i].Pitch = (
					INTERNAL_instancePitches[i] +
					rpcPitch +
					eventPitch +
					INTERNAL_rpcTrackPitches[i]
				);

				/* The final filter is determined by the instance's filter type,
				 * in addition to our calculation of the HF/LF gain values.
				 */
				byte fType = INTERNAL_instancePool[i].FilterType;
				if (fType == 0xFF)
				{
					// No-op, no filter!
				}
				else if (fType == 0)
				{
					INTERNAL_instancePool[i].INTERNAL_applyLowPassFilter(hfGain);
				}
				else if (fType == 1)
				{
					INTERNAL_instancePool[i].INTERNAL_applyHighPassFilter(lfGain);
				}
				else if (fType == 2)
				{
					INTERNAL_instancePool[i].INTERNAL_applyBandPassFilter(hfGain, lfGain);
				}
				else
				{
					throw new InvalidOperationException("Unhandled filter type!");
				}

				// Update 3D position, if applicable
				if (INTERNAL_isPositional)
				{
					INTERNAL_instancePool[i].Apply3D(
						INTERNAL_listener,
						INTERNAL_emitter
					);
				}
			}

			return true;
		}
예제 #56
0
    private void Update()
    {
        LockToCamera();

        switch (fadeMode)
        {
        default:
            break;

        case FadeMode.onlyFadeStart:
            time += Time.deltaTime;

            if (time >= timePerFade)
            {
                time = timePerFade;

                fadeMode = FadeMode.Done;
            }

            break;

        case FadeMode.FadeStart:
            time += Time.deltaTime;

            if (time >= timePerFade)
            {
                time = timePerFade;

                fadeMode = FadeMode.Wait;
            }

            break;

        case FadeMode.FadeEnd:
            time -= Time.deltaTime;

            if (time <= 0)
            {
                fadeMode = FadeMode.Done;      // Will destroy next frame
            }
            break;

        case FadeMode.Wait:
            //Debug.Log(loadOperation.allowSceneActivation + " " + loadOperation.isDone + " " + loadOperation.progress);
            if (loadOperation != null)
            {
                if (loadOperation.isDone == true || loadOperation.progress >= 0.9f)
                {
                    loadOperation.allowSceneActivation = true;

                    fadeMode = FadeMode.FadeEnd;
                }
                else
                {
                    // continue waiting
                }
            }
            else
            {
                fadeMode = FadeMode.FadeEnd;      // no point waiting if there's nothing to load
            }
            break;

        case FadeMode.Done:
            Destroy(this.gameObject);
            break;
        }

        float fadeFactor = time / timePerFade;

        HandleFade(fadeFactor);
    }
예제 #57
0
파일: Cue.cs 프로젝트: clarvalon/FNA
		internal void INTERNAL_startFadeOut(ushort ms)
		{
			INTERNAL_fadeStart = INTERNAL_timer.ElapsedMilliseconds;
			INTERNAL_fadeEnd = ms;
			INTERNAL_fadeMode = FadeMode.FadeOut;
		}
예제 #58
0
 // =========== GRAPHIC ========= //
 public static IEnumerator FadeAlpha(this Graphic graphic, float value, float step, FadeMode fadeMode = FadeMode.LERP)
 {
     while (!graphic.color.a.SafeEquals(value))
     {
         Color c = graphic.color;
         c.a = (fadeMode == FadeMode.LERP) ? Mathf.Lerp(c.a, value, step) :
               Mathf.MoveTowards(c.a, value, step);
         graphic.color = c;
         yield return(null);
     }
 }
예제 #59
0
    private IEnumerator FadeAnimation(FadeMode mode, float duration) {
        _currentFadeMode = mode;
        float startTime = _gameTime.CurrentUnitySessionTime;

        if (mode == FadeMode.In) {
            // Calculate the time we need to fade in from the current alpha as may have started from a partial alpha
            float internalDuration = duration - (duration * _panel.alpha);
            float endTime = startTime + internalDuration;

            while (_gameTime.CurrentUnitySessionTime < endTime) {
                float remainingTime = endTime - _gameTime.CurrentUnitySessionTime;
                float elapsedTime = internalDuration - remainingTime;
                _panel.alpha = elapsedTime / internalDuration;
                yield return null;
            }

            // Make sure it's 1
            _panel.alpha = Constants.OneF;
            EventDelegate.Execute(onShowComplete);
        }
        else if (mode == FadeMode.Out) {
            // Calculate the time we need to fade out from the current alpha as may have started from a partial alpha
            float internalDuration = duration * _panel.alpha;
            float endTime = startTime + internalDuration;

            while (_gameTime.CurrentUnitySessionTime < endTime) {
                float remainingTime = endTime - _gameTime.CurrentUnitySessionTime;
                _panel.alpha = remainingTime / internalDuration;
                yield return null;
            }

            // Make sure it's 0
            _panel.alpha = Constants.ZeroF;
            EventDelegate.Execute(onHideComplete);
            ContentHolder.gameObject.SetActive(false);
        }
        _currentFadeMode = FadeMode.None;
    }
예제 #60
0
        internal static void SetBitmap(ImageView target, Context context, Bitmap bitmap, LoadedFrom loadedFrom, FadeMode fadeMode)
        {
            Drawable placeholder = target.Drawable;
            var      drawable    = new PicassoDrawable(context, bitmap, placeholder, loadedFrom, fadeMode);

            target.SetImageDrawable(drawable);
        }