Ejemplo n.º 1
0
    void Update()
    {
        if (isEnabled)
        {
            //sampleChannel = Mathf.Clamp(sampleChannel, 0, 1); //force the channel to be valid

            if (sourceType != SourceType.Custom)
            {
                if (sourceType == SourceType.AudioListener)
                {
#if WEB_MODE
                    SSWebInteract.GetSpectrumData(spectrum);                            //get the spectrum data from the JS lib
#else
                    AudioListener.GetSpectrumData(spectrum, sampleChannel, windowUsed); //get the spectrum data
                    //Debug.Log(spectrum[0]);
#endif
                }
                else
                {
                    audioSource.GetSpectrumData(spectrum, sampleChannel, windowUsed); //get the spectrum data
                }
            }

#if UNITY_EDITOR    //allows for editing curve while in play mode, disabled in build for optimisation
            float spectrumLength = bars.Length * (1 + barXSpacing);
            float midPoint       = spectrumLength / 2;

            float   curveAngleRads = 0, curveRadius = 0, halfwayAngleR = 0, halfwayAngleD = 0;
            Vector3 curveCentreVector = Vector3.zero;
            if (barCurveAngle > 0)
            {
                curveAngleRads = (barCurveAngle / 360) * (2 * Mathf.PI);
                curveRadius    = spectrumLength / curveAngleRads;

                halfwayAngleR     = curveAngleRads / 2;
                halfwayAngleD     = barCurveAngle / 2;
                curveCentreVector = new Vector3(0, 0, -curveRadius);
                if (barCurveAngle == 360)
                {
                    curveCentreVector = new Vector3(0, 0, 0);
                }
            }
#endif
#if WEB_MODE
            float freqLim = frequencyLimitHigh * 0.76f; //AnalyserNode.getFloatFrequencyData doesn't fill the array, for some reason
#else
            float freqLim = frequencyLimitHigh;
#endif

            for (int i = 0; i < bars.Length; i++)
            {
                Transform bar = bars [i];

                float value;
                float trueSampleIndex;

                //GET SAMPLES
                if (useLogarithmicFrequency)
                {
                    //LOGARITHMIC FREQUENCY SAMPLING

                    //trueSampleIndex = highFrequencyTrim * (highestLogFreq - Mathf.Log(barAmount + 1 - i, 2)) * logFreqMultiplier; //old version

                    trueSampleIndex = Mathf.Lerp(frequencyLimitLow, freqLim, (highestLogFreq - Mathf.Log(barAmount + 1 - i, 2)) / highestLogFreq) * frequencyScaleFactor;

                    //'logarithmic frequencies' just means we want to bias to the lower frequencies.
                    //by doing log2(max(i)) - log2(max(i) - i), we get a flipped log graph
                    //(make a graph of log2(64)-log2(64-x) to see what I mean)
                    //this isn't finished though, because that graph doesn't actually map the bar index (x) to the spectrum index (y).
                    //then we divide by highestLogFreq to make the graph to map 0-barAmount on the x axis to 0-1 in the y axis.
                    //we then use this to Lerp between frequency limits, and then an index is calculated.
                    //also 1 gets added to barAmount pretty much everywhere, because without it, the log hits (barAmount-1,max(freq))
                }
                else
                {
                    //LINEAR (SCALED) FREQUENCY SAMPLING
                    //trueSampleIndex = i * linearSampleStretch; //don't like this anymore

                    trueSampleIndex = Mathf.Lerp(frequencyLimitLow, freqLim, ((float)i) / barAmount) * frequencyScaleFactor;
                    //sooooo this one's gotten fancier...
                    //firstly a lerp is used between frequency limits to get the 'desired frequency', then it's divided by the outputSampleRate (/2, who knows why) to get its location in the array, then multiplied by numSamples to get an index instead of a fraction.
                }

                //the true sample is usually a decimal, so we need to lerp between the floor and ceiling of it.

                int sampleIndexFloor = Mathf.FloorToInt(trueSampleIndex);
                sampleIndexFloor = Mathf.Clamp(sampleIndexFloor, 0, spectrum.Length - 2);                                                 //just keeping it within the spectrum array's range

                value = Mathf.SmoothStep(spectrum[sampleIndexFloor], spectrum[sampleIndexFloor + 1], trueSampleIndex - sampleIndexFloor); //smoothly interpolate between the two samples using the true index's decimal.

                //MANIPULATE & APPLY SAMPLES
                if (multiplyByFrequency) //multiplies the amplitude by the true sample index
                {
#if WEB_MODE
                    value = value * (Mathf.Log(trueSampleIndex + 1) + 1);  //different due to how the WebAudioAPI outputs spectrum data.
#else
                    value = value * (trueSampleIndex + 1);
#endif
                }

#if !WEB_MODE
                value = Mathf.Sqrt(value); //compress the amplitude values by sqrt(x)
#endif

                //DAMPENING
                //Vector3 oldScale = bar.localScale;
                float oldYScale = oldYScales[i], newYScale;
                if (value * barYScale > oldYScale)
                {
                    newYScale = Mathf.Lerp(oldYScale, Mathf.Max(value * barYScale, barMinYScale), attackDamp);
                }
                else
                {
                    newYScale = Mathf.Lerp(oldYScale, Mathf.Max(value * barYScale, barMinYScale), decayDamp);
                }

                bar.localScale = new Vector3(barXScale, newYScale, 1);

                oldYScales[i] = newYScale;

                //set colour
                if (useColorGradient && materialColourCanBeUsed)
                {
                    float newColorVal = colorValueCurve.Evaluate(value);
                    float oldColorVal = oldColorValues[i];

                    if (newColorVal > oldColorVal)
                    {
                        if (colorAttackDamp != 1)
                        {
                            newColorVal = Mathf.Lerp(oldColorVal, newColorVal, colorAttackDamp);
                        }
                    }
                    else
                    {
                        if (colorDecayDamp != 1)
                        {
                            newColorVal = Mathf.Lerp(oldColorVal, newColorVal, colorDecayDamp);
                        }
                    }

                    barMaterials[i].SetFloat(materialValId, newColorVal);

                    oldColorValues[i] = newColorVal;
                }

#if UNITY_EDITOR
                //realtime modifications for Editor only
                if (barCurveAngle > 0)
                {
                    float position      = ((float)i / bars.Length);
                    float thisBarAngleR = (position * curveAngleRads) - halfwayAngleR;
                    float thisBarAngleD = (position * barCurveAngle) - halfwayAngleD;
                    bar.localRotation = Quaternion.Euler(barXRotation, thisBarAngleD, 0);
                    bar.localPosition = new Vector3(Mathf.Sin(thisBarAngleR) * curveRadius, 0, Mathf.Cos(thisBarAngleR) * curveRadius) + curveCentreVector;
                }
                else
                {
                    bar.localPosition = new Vector3(i * (1 + barXSpacing) - midPoint, 0, 0);
                }
#endif
            }
        }
        else           //switched off
        {
            foreach (Transform bar in bars)
            {
                bar.localScale = Vector3.Lerp(bar.localScale, new Vector3(1, barMinYScale, 1), decayDamp);
            }
        }
        if ((Time.unscaledTime - lastMicRestartTime) > micRestartWait)
        {
            RestartMicrophone();
        }
    }
Ejemplo n.º 2
0
    private void UpdateSamples()
    {
        // Sample audio source data
        AudioListener.GetSpectrumData(samples, channel, FFTWindow.Blackman);

        float low = 0, mid = 0, high = 0, average = 0;
        int   lowCount = 0, midCount = 0, highCount = 0, averageCount = 0;

        // Get band data
        for (int i = (int)(lowRange.x / maxRange * sampleCount); i < (int)(lowRange.y / maxRange * sampleCount); i++)
        {
            //if (i < 0 || i >= sampleCount) break;
            low      += samples[i];
            lowCount += 1;
        }
        for (int i = (int)(midRange.x / maxRange * sampleCount); i < (int)(midRange.y / maxRange * sampleCount); i++)
        {
            //if (i < 0 || i >= sampleCount) break;
            mid      += samples[i];
            midCount += 1;
        }
        for (int i = (int)(highRange.x / maxRange * sampleCount); i < (int)(highRange.y / maxRange * sampleCount); i++)
        {
            //if (i < 0 || i >= sampleCount) break;
            high      += samples[i];
            highCount += 1;
        }
        for (int i = (int)(averageRange.x / maxRange * sampleCount); i < (int)(averageRange.y / maxRange * sampleCount); i++)
        {
            //if (i < 0 || i >= sampleCount) break;
            average      += samples[i];
            averageCount += 1;
        }

        // Average band data
        if (lowCount > 0)
        {
            low /= lowCount;
        }
        if (midCount > 0)
        {
            mid /= midCount;
        }
        if (highCount > 0)
        {
            high /= highCount;
        }
        if (averageCount > 0)
        {
            average /= averageCount;
        }

        // Naturally lower normalization scale
        lowMax     = Mathf.Lerp(lowMax, normalizationRange.x, Time.deltaTime * normalizationSpeed);
        midMax     = Mathf.Lerp(midMax, normalizationRange.x, Time.deltaTime * normalizationSpeed);
        highMax    = Mathf.Lerp(highMax, normalizationRange.x, Time.deltaTime * normalizationSpeed);
        averageMax = Mathf.Lerp(averageMax, normalizationRange.x, Time.deltaTime * normalizationSpeed);

        // Reset normalization scale if peaking
        if (low > lowMax)
        {
            lowMax = low;
        }
        if (mid > midMax)
        {
            midMax = mid;
        }
        if (high > highMax)
        {
            highMax = high;
        }
        if (average > averageMax)
        {
            averageMax = average;
        }

        // Clamp values
        if (lowMax > normalizationRange.y)
        {
            lowMax = normalizationRange.y;
        }
        if (midMax > normalizationRange.y)
        {
            midMax = normalizationRange.y;
        }
        if (highMax > normalizationRange.y)
        {
            highMax = normalizationRange.y;
        }
        if (averageMax > normalizationRange.y)
        {
            averageMax = normalizationRange.y;
        }

        // Normalize
        low     /= lowMax;
        mid     /= midMax;
        high    /= highMax;
        average /= averageMax;

        // Adjust public values smoothly
        IntensityLow     = Mathf.Lerp(IntensityLow, low, Time.deltaTime * (low > IntensityLow ? riseSpeed : fallSpeed));
        IntensityMid     = Mathf.Lerp(IntensityMid, mid, Time.deltaTime * (mid > IntensityMid ? riseSpeed : fallSpeed));
        IntensityHigh    = Mathf.Lerp(IntensityHigh, high, Time.deltaTime * (high > IntensityHigh ? riseSpeed : fallSpeed));
        IntensityAverage = Mathf.Lerp(IntensityAverage, average, Time.deltaTime * (average > IntensityAverage ? riseSpeed : fallSpeed));

        // Set debug slider values to help see response
        lowDebug     = IntensityLow;
        midDebug     = IntensityMid;
        highDebug    = IntensityHigh;
        averageDebug = IntensityAverage;
    }
Ejemplo n.º 3
0
 public static float[] RetuenSpectrumData()
 {
     AudioListener.GetSpectrumData(_s, 0, FFTWindow.Rectangular);
     return(_s);
 }
Ejemplo n.º 4
0
 public static void FillSamples(float[] samples, int channel)
 {
     AudioListener.GetSpectrumData(samples, channel, FFTWindow.Hamming);
 }
Ejemplo n.º 5
0
    // Update is called once per frame
    void Update()
    {
        float[] spectrum = new float[1024];
        AudioListener.GetSpectrumData(spectrum, 0, FFTWindow.Hamming);
        float l1 = spectrum [0] + spectrum [2] + spectrum [4];
        float l2 = spectrum [10] + spectrum [11] + spectrum [12];
        float l3 = spectrum[20] + spectrum [21] + spectrum [22];
        float l4 = spectrum [40] + spectrum [41] + spectrum [42] + spectrum [43];
        float l5 = spectrum [80] + spectrum [81] + spectrum [82] + spectrum [83];
        float l6 = spectrum [160] + spectrum [161] + spectrum [162] + spectrum [163];
        float l7 = spectrum [320] + spectrum [321] + spectrum [322] + spectrum [323];

        //Debug.Log(l1 + " " + l2 + " " + l3 + " " + l4 + " " + l5 + " " + l6 + " " + l7);
        text.text = l1 + " " + l2 + " " + l3 + " " + l4 + " " + l5 + " " + l6 + " " + l7;
        GameObject [] cubes = GameObject.FindGameObjectsWithTag("notes");

        for (int i = 1; i < cubes.Length; i++)
        {
            switch (cubes[i].name)
            {
            case "Mi":
                if (l1 > 0.2)
                {
                    cubes [i].gameObject.GetComponent <Renderer> ().material.color = Color.red;
                }
                break;

            case "Si":
                if (l2 > 0.2)
                {
                    cubes[i].gameObject.GetComponent <Renderer> ().material.color = Color.red;
                }
                break;

            case "Sol":
                if (l3 > 0.2)
                {
                    cubes[i].gameObject.GetComponent <Renderer> ().material.color = Color.red;
                }
                break;

            case "Re":
                if (l4 > 0.2)
                {
                    cubes[i].gameObject.GetComponent <Renderer> ().material.color = Color.red;
                }
                break;

            case "La":
                if (l5 > 0.2)
                {
                    cubes[i].gameObject.GetComponent <Renderer> ().material.color = Color.red;
                }
                break;

            case "MI":
                if (l6 > 0.2)
                {
                    cubes[i].gameObject.GetComponent <Renderer> ().material.color = Color.red;
                }
                break;
            }
        }
    }
Ejemplo n.º 6
0
    void Update()
    {
        if (isEnabled)
        {
            //sampleChannel = Mathf.Clamp(sampleChannel, 0, 1); //force the channel to be valid

            if (sourceType != SourceType.Custom)
            {
                if (sourceType == SourceType.AudioListener)
                {
                    AudioListener.GetSpectrumData(spectrum, sampleChannel, windowUsed); //get the spectrum data
                }
                else
                {
                    audioSource.GetSpectrumData(spectrum, sampleChannel, windowUsed); //get the spectrum data
                }
            }

#if UNITY_EDITOR    //allows for editing curve while in play mode, disabled in build for optimisation
            float spectrumLength = bars.Length * (1 + barXSpacing);
            float midPoint       = spectrumLength / 2;

            float   curveAngleRads = 0, curveRadius = 0, halfwayAngleR = 0, halfwayAngleD = 0;
            Vector3 curveCentreVector = Vector3.zero;
            if (barCurveAngle > 0)
            {
                curveAngleRads = (barCurveAngle / 360) * (2 * Mathf.PI);
                curveRadius    = spectrumLength / curveAngleRads;

                halfwayAngleR     = curveAngleRads / 2;
                halfwayAngleD     = barCurveAngle / 2;
                curveCentreVector = new Vector3(0, 0, -curveRadius);
                if (barCurveAngle == 360)
                {
                    curveCentreVector = new Vector3(0, 0, 0);
                }
            }
#endif

            for (int i = 0; i < bars.Length; i++)
            {
                Transform bar = bars [i];

                float value;
                float trueSampleIndex;

                //GET SAMPLES
                if (useLogarithmicFrequency)
                {
                    //LOGARITHMIC FREQUENCY SAMPLING
                    trueSampleIndex = highFrequencyTrim * (highestLogFreq - Mathf.Log(bars.Length + 1 - i, 2)) * logFreqMultiplier; //gets the index equiv of the logified frequency

                    //^that really needs explaining.
                    //'logarithmic frequencies' just means we want more of the lower frequencies and less of the high ones.
                    //a normal log2 graph will quickly go past 1-5 and spend much more time on stuff above that, but we want the opposite
                    //so by doing log2(max(i)) - log2(max(i) - i), we get a flipped log graph
                    //(make a graph of log2(64)-log2(64-x) to see what I mean)
                    //this isn't finished though, because that graph doesn't actually map the bar index (x) to the spectrum index (y).
                    //logFreqMultiplier stretches the grpah upwards so that the highest value (log2(max(i)))hits the highest frequency.
                    //also 1 gets added to barAmount pretty much everywhere, because without it, the log hits (barAmount-1,max(freq))
                }
                else
                {
                    //LINEAR (SCALED) FREQUENCY SAMPLING
                    trueSampleIndex = i * linearSampleStretch;
                }

                //the true sample is usually a decimal, so we need to lerp between the floor and ceiling of it.

                int sampleIndexFloor = Mathf.FloorToInt(trueSampleIndex);
                sampleIndexFloor = Mathf.Clamp(sampleIndexFloor, 0, spectrum.Length - 2);                                 //just keeping it within the spectrum array's range

                float sampleIndexDecimal = trueSampleIndex % 1;                                                           //gets the decimal point of the true sample, for lerping

                value = Mathf.SmoothStep(spectrum[sampleIndexFloor], spectrum[sampleIndexFloor + 1], sampleIndexDecimal); //smoothly interpolate between the two samples using the true index's decimal.

                //MANIPULATE & APPLY SAMPLES
                if (multiplyByFrequency) //multiplies the amplitude by the true sample index
                {
                    value = value * (trueSampleIndex + 1);
                }

                value = Mathf.Sqrt(value); //compress the amplitude values by sqrt(x)


                //DAMPENING
                //Vector3 oldScale = bar.localScale;
                float oldYScale = oldYScales[i], newYScale;
                if (value * barYScale > oldYScale)
                {
                    newYScale = Mathf.Lerp(oldYScale, Mathf.Max(value * barYScale, barMinYScale), attackDamp);
                }
                else
                {
                    newYScale = Mathf.Lerp(oldYScale, Mathf.Max(value * barYScale, barMinYScale), decayDamp);
                }

                bar.localScale = new Vector3(barXScale, newYScale, 1);

                oldYScales[i] = newYScale;

                //set colour
                if (useColorGradient && materialColourCanBeUsed)
                {
                    float newColorVal = colorValueCurve.Evaluate(value);
                    float oldColorVal = oldColorValues[i];

                    if (newColorVal > oldColorVal)
                    {
                        if (colorAttackDamp != 1)
                        {
                            newColorVal = Mathf.Lerp(oldColorVal, newColorVal, colorAttackDamp);
                        }
                    }
                    else
                    {
                        if (colorDecayDamp != 1)
                        {
                            newColorVal = Mathf.Lerp(oldColorVal, newColorVal, colorDecayDamp);
                        }
                    }

                    barMaterials[i].SetFloat(materialValId, newColorVal);

                    oldColorValues[i] = newColorVal;
                }

#if UNITY_EDITOR
                //realtime modifications for Editor only
                if (barCurveAngle > 0)
                {
                    float position      = ((float)i / bars.Length);
                    float thisBarAngleR = (position * curveAngleRads) - halfwayAngleR;
                    float thisBarAngleD = (position * barCurveAngle) - halfwayAngleD;
                    bar.localRotation = Quaternion.Euler(barXRotation, thisBarAngleD, 0);
                    bar.localPosition = new Vector3(Mathf.Sin(thisBarAngleR) * curveRadius, 0, Mathf.Cos(thisBarAngleR) * curveRadius) + curveCentreVector;
                }
                else
                {
                    bar.localPosition = new Vector3(i * (1 + barXSpacing) - midPoint, 0, 0);
                }
#endif
            }
        }
        else           //switched off
        {
            foreach (Transform bar in bars)
            {
                bar.localScale = Vector3.Lerp(bar.localScale, new Vector3(1, barMinYScale, 1), decayDamp);
            }
        }
        if ((Time.unscaledTime - lastMicRestartTime) > micRestartWait)
        {
            RestartMicrophone();
        }
    }
Ejemplo n.º 7
0
    // Update is called once per frame
    void Update()
    {
        AudioListener.GetSpectrumData(history[historyInd % history.Count], 0, FFTWindow.Rectangular);
        historyInd++;
        for (int i = 0; i < fftSize; i++)
        {
            result[i] = history[0][i];
        }

        for (int j = 1; j < history.Count; j++)
        {
            var hs = history[j];
            for (int i = 0; i < fftSize; i++)
            {
                result[i] += hs[i];
            }
        }

        foreach (Filter filter in filters)
        {
            filter.max = 0;
            filter.min = 1;
        }

        for (int i = 0; i < fftSize; i++)
        {
            foreach (Filter filter in filters)
            {
                float v    = result[i] / history.Count;
                float band = 44100 / fftSize * i;
                if (filter.inclusive && band > filter.low && band < filter.high)
                {
                    filter.max = Mathf.Max(v, filter.max);
                    filter.min = Mathf.Min(v, filter.min);
                }
                else if (!filter.inclusive && (band < filter.low || band > filter.high))
                {
                    filter.max = Mathf.Max(v, filter.max);
                    filter.min = Mathf.Min(v, filter.min);
                }
            }
        }

        //Update the effects
        int c = 0;

        foreach (PostProcessVolume ppVolume in ppBehaviour)
        {
            c++;
            var ppProfile = ppVolume.profile;

            var vignetSettings = ppProfile.GetSetting <Vignette>();

            vignetSettings.intensity.value = Mathf.Clamp(filters[0].max * 1f + 0.10f, 0f, 0.25f);
            //ppProfile.vignette.settings = vignetSettings;

            var bloomSettings = ppProfile.GetSetting <Bloom>();
            bloomSettings.intensity.value = 5.0f + Mathf.SmoothStep(0.0f, 1.8f, filters[1].max * 3.2f);
            //ppProfile.bloom.settings = bloomSettings;

            var rgbSettings = ppProfile.GetSetting <RGBShift>();

            if (filters[2].max > 0.02f)
            {
                rgbSettings.bShift.value = (filters[2].max - 0.02f) * 0.05f;
                rgbSettings.gShift.value = -(filters[2].max - 0.02f) * 0.05f;
            }
            else
            {
                rgbSettings.bShift.value = 0; // Mathf.SmoothStep(0.0f, 0.02f, filters[2].max);
                rgbSettings.gShift.value = 0; // -Mathf.SmoothStep(0.0f, 0.02f, filters[2].max);
            }

            var distortSettings = ppProfile.GetSetting <Distort>();
            distortSettings.intensity.value = Mathf.SmoothStep(0f, 0.4f, filters[2].min * 55f);
            distortSettings.posOff.value    = UnityEngine.Random.value;

            // Pixelate pixelate;
            // var pixelateFound = ppProfile.TryGetSettings<Pixelate>(out pixelate);
            if (c == 3)
            {
                //   pixelate.pixelate.value = new Vector2(filters[0].max * Screen.width / 2 + Screen.width / 4, filters[0].max * Screen.height / 2 + Screen.height / 4);
                distortSettings.intensity.value = Mathf.SmoothStep(0f, 0.4f, (filters[0].max + filters[1].max + filters[2].max) * 25f) + 0.25f;
            }
        }

        if (ppBehaviour.Length > 0)
        {
            ppBehaviour[0].weight = Mathf.Clamp(1f - blend, 0f, 1f);
        }
        if (ppBehaviour.Length > 1)
        {
            ppBehaviour[1].weight = Mathf.Clamp(blend < 1f ? blend : 2f - blend, 0f, 1f);
        }
        if (ppBehaviour.Length > 2)
        {
            ppBehaviour[2].weight = Mathf.Clamp(blend < 2f ? blend - 1f : 3f - blend, 0f, 1f);
        }
        if (ppBehaviour.Length > 3)
        {
            ppBehaviour[3].weight = Mathf.Clamp(blend < 3f ? blend - 2f : 4f - blend, 0f, 1f);
        }
        if (ppBehaviour.Length > 4)
        {
            ppBehaviour[4].weight = Mathf.Clamp(blend < 4f ? blend - 3f : 5f - blend, 0f, 1f);
        }

        //    blend += Time.deltaTime / 10f;
        //    if (blend > 4f) blend = 0f;
    }
Ejemplo n.º 8
0
 void Update()
 {
     AudioListener.GetSpectrumData(spectrum, 0, FFTWindow.Rectangular);
     transform.localScale = originalScale + Vector3.one * (spectrum[3] * 0.1f);
 }
Ejemplo n.º 9
0
    private void OnGUI()
    {
        //m_FreqCrossover[0] = m_FreqCrossoverLowestFreq;
        //for (int i = 1; i < m_FreqCrossover.Length; i++)
        //{
        //    m_FreqCrossover[i] = m_FreqCrossover[i - 1] * m_BandRatio;
        //}

        if (m_UseListener)
        {
            AudioListener.GetSpectrumData(m_SpectrumLeft, 0, FFTWindow.Rectangular);
            AudioListener.GetSpectrumData(m_SpectrumRight, 1, FFTWindow.Rectangular);
        }
        else if (m_AudioSource)
        {
            m_AudioSource.GetSpectrumData(m_SpectrumLeft, 0, FFTWindow.Rectangular);
        }

        //GuiHelper.SetOrigin(GuiHelper.Origin.BottomLeft);

        float spectrumFreq = 0.0f;
        int   freqBand     = 0;
        //float barWidth = m_HScale;
        float maxValue = 0.0f;

        //float accumValue = 0.0f;
        //int accumCount = 0;
        //float average = 0.0f;
        //float power = 0.0f;
        for (int i = 0; i < m_SpectrumSize; ++i)
        {
            maxValue = Mathf.Max(maxValue, m_SpectrumLeft[i]);
            maxValue = Mathf.Max(maxValue, m_SpectrumRight[i]);

            //accumValue += m_SpectrumLeft[i];
            //accumValue += m_SpectrumRight[i];
            //accumCount += 2;

            //if (m_SpectrumLeft[i] > 0.0001f) // arbitrary cut-off to filter out noise
            //{
            //	average += m_SpectrumLeft[i] * spectrumFreq;
            //	power += m_SpectrumLeft[i];
            //}
            //if (m_SpectrumRight[i] > 0.0001f) // arbitrary cut-off to filter out noise
            //{
            //	average += m_SpectrumRight[i] * spectrumFreq;
            //	power += m_SpectrumRight[i];
            //}

            spectrumFreq += m_SpectrumFreqStep;

            if (spectrumFreq >= m_FreqCrossover[freqBand] || i == (m_SpectrumSize - 1))
            {
                // decibels relative to full scale
                float dBFS = 20.0f * Mathf.Log10(maxValue);                             // range -infinity -> 0

                // clamp to desired dB range for bar graph
                float value = Mathf.Clamp01(1.0f + (dBFS / m_dBRange));                         // range 0.0 -> 1.0
                SpectrumValues[freqBand] = value;

                if (DebugDraw)
                {
                    ////float centre_x = Screen.width / 2 - (m_FreqCrossover.Length / 2) * barWidth + (freqBand + 0.5f) * barWidth;

                    ////if (InvertedDebugDraw)
                    ////{
                    ////    Vector2 bottom = new Vector2(centre_x, Screen.height - value * m_VScale);
                    ////    Vector2 top = new Vector2(centre_x, Screen.height);
                    ////    //GuiHelper.DrawLine(bottom, top, m_BarTexture, barWidth);
                    ////}
                    ////else
                    ////{
                    ////    Vector2 bottom = new Vector2(centre_x, 0);
                    ////    Vector2 top = new Vector2(centre_x, value * m_VScale);
                    ////    //GuiHelper.DrawLine(bottom, top, m_BarTexture, barWidth);
                    ////}
                }

                // reset for next frequency band
                maxValue = 0.0f;
                //accumValue = 0.0f;
                //accumCount = 0;

                freqBand++;
                if (freqBand >= m_FreqCrossover.Length || freqBand >= SpectrumValues.Length)
                {
                    break;
                }
            }
        }

        // find dominant frequency
        //float dominantHz = (power > 0.0001f) ? (average / power) : 0.0f;
        //Utils.Log(dominantHz.ToString("0"));
    }
Ejemplo n.º 10
0
    // Update is called once per frame
    void Update()


    {
        float[] spectrum = new float[256];

        AudioListener.GetSpectrumData(spectrum, 0, FFTWindow.Rectangular);
        Debug.Log(Mathf.Log(spectrum[0]));
        multiplyer = Mathf.Abs(Mathf.Round(spectrum[0]) + 1);
        for (int i = 1; i < spectrum.Length - 1; i++)
        {
            Debug.DrawLine(new Vector3(i - 1, Mathf.Log(spectrum[i - 1]) + 10, 2), new Vector3(i - 1, Mathf.Log(spectrum[i - 1]) + 15, 2), Color.cyan);
        }

        startTime -= Time.deltaTime;

        if (Input.GetKeyDown(KeyCode.P))
        {
            //ShuffleList();
            //InitBoard();
            Start();
        }
        //shuffle board ends

        CheckGrid();
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay
                          (Input.mousePosition);
            RaycastHit2D hit =
                Physics2D.GetRayIntersection(ray, 1000);

            if (hit)
            {
                tile1 = hit.collider.gameObject;
            }
        }
        // if finger up is detected after
        // an initial tile has been chosen
        else if (Input.GetMouseButtonUp(0) && tile1)
        {
            Ray ray = Camera.main.ScreenPointToRay
                          (Input.mousePosition);
            RaycastHit2D hit =
                Physics2D.GetRayIntersection(ray, 1000);

            if (hit)
            {
                tile2 = hit.collider.gameObject;
            }

            if (tile1 && tile2)
            {
                int horzDist = (int)
                               Mathf.Abs(tile1.transform.position.x -
                                         tile2.transform.position.x);
                int vertDist = (int)
                               Mathf.Abs(tile1.transform.position.y -
                                         tile2.transform.position.y);

                if (horzDist == 1 ^ vertDist == 1)
                {
                    Tile temp = tiles[(int)tile1.transform.position.x,
                                      (int)tile1.transform.position.y];
                    tiles[(int)tile1.transform.position.x,
                          (int)tile1.transform.position.y] =
                        tiles[(int)tile2.transform.position.x,
                              (int)tile2.transform.position.y];
                    tiles[(int)tile2.transform.position.x,
                          (int)tile2.transform.position.y] = temp;



                    Vector3 tempPos = tile1.transform.position;
                    tile1.transform.position =
                        tile2.transform.position;
                    tile2.transform.position = tempPos;
                    //reset the touched tiles
                    tile1 = null;
                    tile2 = null;
                }
                else
                {
                    GetComponent <AudioSource>().Play();
                }
            }
        }
    }
Ejemplo n.º 11
0
    void Update()
    {
        float[] spectrum = new float[1024]; AudioListener.GetSpectrumData(spectrum, 0, FFTWindow.Hamming);
        if (playR)
        {
            if (g > 0)
            {
                g -= changeSpeed * Time.deltaTime;
            }
            r += changeSpeed * Time.deltaTime;
            if (r > 0.6f)
            {
                playB = true;
                playR = false;
            }
        }
        if (playB)
        {
            b += changeSpeed * Time.deltaTime;
            r -= changeSpeed * Time.deltaTime;
            if (b > 0.6f)
            {
                playG = true;
                playB = false;
            }
        }
        if (playG)
        {
            b -= changeSpeed * Time.deltaTime;
            g += changeSpeed * Time.deltaTime;
            if (g > 0.6f)
            {
                playRB = true;
                playG  = false;
            }
        }
        if (playRB)
        {
            if (g > 0)
            {
                g -= changeSpeed * Time.deltaTime;
            }
            if (b < 0.8f && !finishup)
            {
                r += changeSpeed * Time.deltaTime;
                b += changeSpeed * Time.deltaTime * 2;
                if (b > 0.8f)
                {
                    finishup = true;
                }
            }
            if (finishup && !playR)
            {
                r -= changeSpeed * Time.deltaTime;
                b -= changeSpeed * Time.deltaTime;
                if (b < 0.1f)
                {
                    playR    = true;
                    finishup = false;
                    playRB   = false;
                }
            }
        }
        float theLVL  = spectrum[3] * (density);
        float MidLvl  = spectrum[7] * (density);
        float highLvl = spectrum[12] * (density);

        peak     -= 3f * Time.deltaTime;
        MidPeak  -= 3f * Time.deltaTime;
        HighPeak -= 3f * Time.deltaTime;
        Vector3 armsCheck = arms.transform.eulerAngles;

        if (peak > 1)
        {
            rndHead.transform.Rotate(Vector3.forward * 2f * peak);
            rndHead2.transform.Rotate(Vector3.forward * -2f * peak);
        }
        rndHead.transform.Rotate(Vector3.up * 2f);
        rndHead2.transform.Rotate(Vector3.up * -2f);
        checker = armsCheck.x;

        if (armsCheck.x <= 85)
        {
            if (switchArms)
            {
                switchArms = false;
            }
            if (!switchArms)
            {
                switchArms = true;
            }
        }
        if (switchArms && startDance)
        {
            distance += -0.1f;
            arms.transform.Rotate(Vector3.up * 0.1f);
            hands.transform.Rotate(Vector3.up * 0.1f);
            legs.transform.Rotate(Vector3.up * -0.1f);
            butt.transform.Rotate(Vector3.up * -0.1f);
        }
        if (!switchArms && startDance)
        {
            arms.transform.Rotate(Vector3.up * -0.1f);
            hands.transform.Rotate(Vector3.up * -0.1f);
            legs.transform.Rotate(Vector3.up * 0.1f);
            butt.transform.Rotate(Vector3.up * 0.1f);
        }
        if (distance < -8.7f)
        {
            switchArms = false;
            distance   = 0;
        }


        if (!spin)
        {
            tiger.transform.Rotate(Vector3.up * (0.5f));
        }
        if (spin)
        {
            tiger.transform.Rotate(Vector3.down * (0.5f));
        }

        if (beatHit)
        {
            if (spectrum[3] * density < 0.6f)
            {
                count++;

                beatHit = false;
            }
        }
        if (spectrum[3] * density > 0.8f && beatHit == false)
        {
            beatHit = true;
            if (!spin && count == 4)
            {
                spin  = true;
                count = 0;
            }
            if (spin && count == 4)
            {
                spin  = false;
                count = 0;
            }
        }
        if (beatHit && tilt)
        {
            tilt = false;
        }
        if (beatHit && !tilt)
        {
            tilt = true;
        }
        Vector3 tiltHead = lego.transform.eulerAngles;

        if (tilt)
        {
            tiltHead.y = 87;
        }
        if (!tilt)
        {
            tiltHead.y = 94;
        }

        if (theLVL > peak)
        {
            peak = theLVL;
        }
        if (MidLvl > MidPeak)
        {
            MidPeak = MidLvl;
        }
        if (highLvl > HighPeak)
        {
            HighPeak = highLvl;
        }



        for (int i = 0; i < numberOfObjects; i++)
        {
            Vector3 TextpreviousScale = text.transform.localScale;
            Vector3 highPrevScale     = picHigh.transform.localScale;
            Vector3 MidPrevScale      = picLow.transform.localScale;
            Vector3 legoPrevScale     = lego.transform.localScale;
            if (peak < 1)
            {
                TextpreviousScale.x = peak * 1.3f + 1;
                legoPrevScale.y     = peak * 1.3f + 1;
            }
            if (MidPeak < 1)
            {
                MidPrevScale.x = MidPeak + 1;
            }
            if (HighPeak < 1)
            {
                highPrevScale.x = HighPeak * 1.3f + 1;
                legoPrevScale.x = HighPeak * 1.5f + 1;
            }
            if (peak > 1.5f)
            {
                TextpreviousScale.x = peak / 2 + 1;
            }
            if (MidPeak > 1.5f)
            {
                MidPrevScale.x = MidPeak / 15 + 1;
            }
            if (HighPeak > 1.5f)
            {
                highPrevScale.x = HighPeak / 10 + 1;
                legoPrevScale.x = HighPeak / 8 + 1;
            }
            if (peak > 1.5f)
            {
                TextpreviousScale.x = peak / 2 + 1;
            }
            if (MidPeak > 1.5f)
            {
                MidPrevScale.x = MidPeak / 15 + 1;
            }
            if (HighPeak > 1.5f)
            {
                highPrevScale.x = HighPeak / 10 + 1;
            }


            text.transform.localScale    = TextpreviousScale;
            picHigh.transform.localScale = highPrevScale;
            picLow.transform.localScale  = MidPrevScale;
            lego.transform.localScale    = legoPrevScale;
            lego.transform.Rotate(Vector3.forward * Time.deltaTime * 1.5f);
            if (colorAdapt)
            {
                text.material.color = new Color(r, g, peak, 0.7f);
            }
            thepic.material.color = new Color(r, g, b, peak);      //spectrum[3] * (density)   <--- for bounce
            MeshRenderer shirtColor = shirt.GetComponent <MeshRenderer>();
            shirtColor.material.color = new Color(r, g, b, peak);


            Vector3 previousScale = cubes[i].transform.localScale;
            previousScale.y = spectrum[i] * 20;
            cubes[i].transform.localScale = previousScale;

            if (spectrum[i] * density < 0.4f)
            {
                changeColors(i, new Color(0, 0, spectrum[i] * 20));
                holdRot += 0.02f;
            }
            if (spectrum[i] * density > 0.4f && spectrum[i] * density < 0.7f)
            {
                changeColors(i, new Color(0, spectrum[i] * density, 0));
                holdRot += 0.2f;
            }
            if (spectrum[i] * density > 0.7f)
            {
                changeColors(i, new Color(spectrum[i] * density - 1, 0, 0));
                holdRot += 5f;
            }
            cubes[i].transform.rotation = Quaternion.Euler(0, holdRot, 0);
        }
    }
    /// <summary>
    /// Updates every frame this instance.
    /// </summary>
    void LateUpdate()
    {
        // Get Spectrum Data from Both Channels of audio
        float [] spectrumLeftData;
        float [] spectrumRightData;


        if (listenAllSounds)
        {
            // Get Spectrum Data from Both Channels of audio
                        #pragma warning disable 618
            spectrumLeftData  = AudioListener.GetSpectrumData(channelValue, 0, method);
            spectrumRightData = AudioListener.GetSpectrumData(channelValue, 1, method);
                        #pragma warning restore 618
        }
        else
        {
            if (audioSource == null)
            {
                Debug.LogWarning("Please assign an AudioSource or Active Listen All Sounds");
                return;
            }

            // Get Spectrum Data from Both Channels of audio
                        #pragma warning disable 618
            spectrumLeftData  = audioSource.GetSpectrumData(channelValue, 0, method);
            spectrumRightData = audioSource.GetSpectrumData(channelValue, 1, method);
                        #pragma warning restore 618
        }

        // Wait for Rhythm Particles Interval (for performance)
        if (remainingRhythmParticlesTime <= 0)
        {
            int   count       = 0;
            float spectrumSum = 0;

            // Using bass data only
            for (int i = 0; i < 40; i++)
            {
                spectrumSum += Mathf.Max(spectrumLeftData [i], spectrumRightData [i]);
                count++;
            }

            rhythmAverage = (spectrumSum / count) * rhythmSensibility;


            // If the spectrum value exceeds the minimum
            if (rhythmAverage >= minRhythmSensibility)
            {
                rhythmSurpassed = true;
            }

            // Auto Rhythm Particles
            if (autoRhythmParticles)
            {
                if (rhythmSurpassed)
                {
                    // Emit particles
                    rhythmParticleSystem.Emit(amountToEmit);
                }
            }
        }


        // Scale SoundBars Normally
        if (!ScaleByRhythm)
        {
            // SoundBars for Left Channel and Right Channel
            for (int i = 0; i < halfBarsValue; i++)
            {
                // Apply Off-Sets to get the AudioSpectrum
                int spectrumLeft  = i * bassHorizontalScale + bassOffset;
                int spectrumRight = i * trebleHorizontalScale + trebleOffset;

                // Get Actual Scale from SoundBar in "i" position
                prevLeftScale  = soundBars [i].transform.localScale;
                prevRightScale = soundBars [i + halfBarsValue].transform.localScale;

                var spectrumLeftValue  = spectrumLeftData [spectrumLeft] * bassSensibility;
                var spectrumRightValue = spectrumRightData [spectrumRight] * trebleSensibility;

                // Left Channel //

                // If Minimum Particle Sensibility is exceeded (volume is clamped beetween 0.01 and 1 to avoid 0)
                if (spectrumLeftValue >= minParticleSensibility)
                {
                    // Apply extra scale to that SoundBar using Lerp
                    newLeftScale = Mathf.Lerp(prevLeftScale.y,
                                              spectrumLeftValue * bassHeight * globalScale,
                                              Time.deltaTime * extraScaleVelocity);

                    // If the Particles are activated, emit a particle too
                    if (soundBarsParticles)
                    {
                        if (remainingParticlesTime <= 0)
                        {
                            soundBars [i].GetComponentInChildren <ParticleSystem> ().Play();

                            surpassed = true;
                        }
                    }
                }
                else
                {
                    newLeftScale = Mathf.Lerp(prevLeftScale.y, spectrumLeftValue * globalScale, Time.deltaTime * smoothVelocity);
                }

                // If the New Scale is greater than Previous Scale, set the New Value to Previous Scale
                if (newLeftScale > prevLeftScale.y)
                {
                    prevLeftScale.y = newLeftScale;
                    leftScale       = prevLeftScale;
                }
                else                     // Else, Lerp to 0.1 value
                {
                    leftScale   = prevLeftScale;
                    leftScale.y = Mathf.Lerp(prevLeftScale.y, 0.1f, Time.deltaTime * smoothVelocity);
                }

                // Set new scale
                soundBars [i].transform.localScale = leftScale;

                // Fix minimum Y Scale
                if (soundBars [i].transform.localScale.y < 0.11f)
                {
                    soundBars [i].transform.localScale = new Vector3(1f, 0.11f, 1f);
                }

                // Right Channel //

                // If Minimum Particle Sensibility is exceeded (volume is clamped beetween 0.01 and 1 to avoid 0)
                if (spectrumRightValue >= minParticleSensibility)
                {
                    // Apply extra scale to that SoundBar using Lerp
                    newRightScale = Mathf.Lerp(prevRightScale.y,
                                               spectrumRightValue * trebleHeight * globalScale,
                                               Time.deltaTime * extraScaleVelocity);

                    // If the Particles are activated, emit a particle too
                    if (soundBarsParticles)
                    {
                        if (remainingParticlesTime <= 0f)
                        {
                            soundBars [i + halfBarsValue].GetComponentInChildren <ParticleSystem> ().Play();

                            surpassed = true;
                        }
                    }
                }
                else
                {
                    newRightScale = Mathf.Lerp(prevRightScale.y, spectrumRightValue * globalScale, Time.deltaTime * smoothVelocity);
                }

                // If the New Scale is greater than Previous Scale, set the New Value to Previous Scale
                if (newRightScale > prevRightScale.y)
                {
                    prevRightScale.y = newRightScale;
                    rightScale       = prevRightScale;
                }
                else                     // Else, Lerp to 0.1
                {
                    rightScale   = prevRightScale;
                    rightScale.y = Mathf.Lerp(prevRightScale.y, 0.1f, Time.deltaTime * smoothVelocity);
                }

                // Set new scale
                soundBars [i + halfBarsValue].transform.localScale = rightScale;

                // Fix minimum Y Scale
                if (soundBars [i + halfBarsValue].transform.localScale.y < 0.11f)
                {
                    soundBars [i + halfBarsValue].transform.localScale = new Vector3(1f, 0.11f, 1f);
                }
            }
        }
        else             // Scale All SoundBars by Rhythm

        {
            for (int i = 0; i < barsQuantity; i++)
            {
                prevLeftScale = soundBars [i].transform.localScale;

                // If Minimum Particle Sensibility is exceeded (volume is clamped beetween 0.01 and 1 to avoid 0)
                if (rhythmSurpassed)
                {
                    // Apply extra scale to that SoundBar using Lerp
                    newLeftScale = Mathf.Lerp(prevLeftScale.y,
                                              rhythmAverage * bassHeight * globalScale,
                                              Time.deltaTime * extraScaleVelocity);

                    // If the Particles are activated, emit a particle too
                    if (soundBarsParticles)
                    {
                        if (remainingParticlesTime <= 0f)
                        {
                            soundBars [i].GetComponentInChildren <ParticleSystem> ().Play();

                            surpassed = true;
                        }
                    }
                }
                else                            // Else, Lerp to the previous scale
                {
                    newLeftScale = Mathf.Lerp(prevLeftScale.y,
                                              rhythmAverage * globalScale,
                                              Time.deltaTime * extraScaleVelocity);
                }

                // If the New Scale is greater than Previous Scale, set the New Value to Previous Scale
                if (newLeftScale > prevLeftScale.y)
                {
                    prevLeftScale.y = newLeftScale;
                    rightScale      = prevLeftScale;
                }
                else                     // Else, Lerp to 0.1
                {
                    rightScale   = prevLeftScale;
                    rightScale.y = Mathf.Lerp(prevLeftScale.y, 0.1f, Time.deltaTime * smoothVelocity);
                }

                // Set new scale
                soundBars [i].transform.localScale = rightScale;

                // Fix minimum Y Scale
                if (soundBars [i].transform.localScale.y < 0.11f)
                {
                    soundBars [i].transform.localScale = new Vector3(1f, 0.11f, 1f);
                }
            }
        }

        // Particles Interval Reset
        if (soundBarsParticles)
        {
            if (surpassed)
            {
                surpassed = false;
                remainingParticlesTime = particlesMaxInterval;
            }
            else
            {
                remainingParticlesTime -= Time.deltaTime;
            }
        }

        // Rhythm Interval Reset
        if (rhythmSurpassed)
        {
            rhythmSurpassed = false;
            remainingRhythmParticlesTime = rhythmParticlesMaxInterval;
        }
        else
        {
            remainingRhythmParticlesTime -= Time.deltaTime;
        }


        // Change Colors
        if (changeColor)
        {
            timeChange -= Time.deltaTime;

            // When the counter are less than 0, change to the next Color
            if (timeChange < 0f)
            {
                NextColor();
            }

            // Execute color lerping
            ChangeColor();
        }

        // Execute Camera Control
        if (cameraControl)
        {
            if (rotateCamera)
            {
                CameraMovement();
            }
        }
    }
Ejemplo n.º 13
0
    // Update is called once per frame
    void Update()
    {
        float[] samples      = new float[numberOfObjects];
        float   currPeak     = 0;
        float   minVal       = Mathf.Infinity;
        float   highestValue = 0;

        AudioListener.GetSpectrumData(samples, 0, FFTWindow.BlackmanHarris);


        /*if (prevData[selectedChannel].upwards)
         *  prevPeak = prevData[selectedChannel].prevValue;*/

        /*if (samples[selectedChannel] >= highestValue) {
         *  for (int i = 0; i < actualNumber; i++) {
         *      if (samples[i] > highestValue) {
         *          highestValue = samples[i];
         *          selectedChannel = i;
         *      }
         *  }
         *  fA = true;
         * } else {
         *  Debug.Log("Working");
         *  if (fA) {
         *      flashValue = 2.5f;
         *      totalBeats++;
         *      combo.text = totalBeats.ToString();
         *      fA = false;
         *  }
         *
         *  if (samples[selectedChannel] < highestValue * 0.1f)
         *      highestValue = samples[selectedChannel];
         * }*/

        if (flashValue > 1.5f)
        {
            flash.transform.localScale = new Vector3(flashValue, flashValue, 0);
            flashValue -= 0.25f;
        }

        bool[] currPos = new bool[2];

        if (selectedChannel > 0)
        {
            currPos[0] = samples[selectedChannel] - samples[selectedChannel - 1] > 0 ? true : false;
        }
        else
        {
            currPos[0] = true;
        }

        if (selectedChannel < samples.Length - 1)
        {
            currPos[1] = samples[selectedChannel + 1] - samples[selectedChannel] > 0 ? true : false;
        }
        else
        {
            currPos[1] = false;
        }

        for (int i = 0; i < actualNumber; i++)
        {
            Vector3 previousScale = cubes[i].transform.localScale;
            previousScale.y = samples[i] * 100;
            cubes[i].transform.localScale = previousScale;

            Vector3 pos = cubes[i].transform.position;
            pos.y = cubes[i].transform.localScale.y / 2;
            cubes[i].transform.position = pos;
        }

        bool hasTrue = false;

        for (int j = 0; j < currPos.Length; j++)
        {
            if (isPrevHigh[j] == currPos[j])
            {
                hasTrue = true;
            }
        }

        isPrevHigh = currPos;

        if (hasTrue)
        {
            return;
        }

        cubesShadow[selectedChannel].transform.position = new Vector3(cubesShadow[selectedChannel].transform.position.x, samples[selectedChannel] * 100);
        //Debug.DrawRay(new Vector2(-100, pV[selectedChannel] * 100), new Vector2(200, 0), Color.red, 1f);

        for (int i = 0; i < actualNumber; i++)
        {
            if (samples[i] > highestValue)
            {
                highestValue    = samples[i];
                selectedChannel = i;
            }
        }


        flashValue = 2.5f;
        totalBeats++;
        combo.text = totalBeats.ToString();



        //isPrevHigh = currPos;

        /*if (cP < 2)
         *  pD[0] = 0;
         * else {
         *  float v = samples[cP] - samples[cP - 1];
         *  pD[0] = v / Mathf.Abs(v);
         * }
         *
         * if (cP > actualNumber - 2)
         *  pD[1] = 0;
         * else {
         *  float v = samples[cP + 1] - samples[cP];
         *  pD[1] = v / Mathf.Abs(v);
         * }*/


        /*
         * //Debug.Log(minVal);
         *
         * if (/*!prevData[selectedChannel].upwardscurrPeak - prevValue < 0 && currPeak - lowestValue >= minOnset) {
         *  //targetChanged = false;
         *  flashValue = 2.5f;
         *  //prevRenderer = cubes[currentTarget].GetComponent<Renderer>();
         *  //prevRenderer.material.color = Color.red;
         *  bpmTracker++;
         *  totalBeats++;
         *  valueChanged = false;
         *  combo.text = totalBeats.ToString();
         *  Debug.Log(currPeak - lowestValue);
         *  Debug.DrawRay(new Vector2(cubes[0].transform.position.x, prevValue * 50), new Vector2(numberOfObjects, 0), Color.black, 0.1f);
         *  // Bullet inst = Instantiate(projectile, flash.transform.position, Quaternion.identity);
         *  //inst.angle = (totalBeats * 15 * Mathf.PI * 2) / 360;
         *  //Destroy(inst.gameObject, 5);
         *  //cubesShadow[selectedChannel].transform.localScale = peakScale;
         *  //cubesShadow[selectedChannel].transform.position = peakHeight;
         *  //cubesShadow[selectedChannel].material.color = new Color(cubesShadow[selectedChannel].material.color.r, cubesShadow[selectedChannel].material.color.g, cubesShadow[selectedChannel].material.color.b, 1);
         * }
         *
         * if (currPeak - prevValue < 0)
         *  lowestValue = currPeak;
         *
         * prevValue = currPeak;
         */

        //for (int i = 0; i < cubesShadow.Count; i++)
        //cubesShadow[i].material.color = new Color(cubesShadow[i].material.color.r, cubesShadow[i].material.color.g, cubesShadow[i].material.color.b, cubesShadow[i].material.color.a - 0.01f);


        //if (flashValue > 0) {
        //Color color = Random.ColorHSV();
        //flash.color = new Color(color.r, color.g, color.b, flashValue);
        //flashValue -= 0.1f;
        //}



        if (samples[selectedChannel] < pV[selectedChannel])
        {
            if (samples[selectedChannel] - lV[selectedChannel] >= lV[selectedChannel])
            {
                //cubesShadow[selectedChannel].transform.position = new Vector3(cubesShadow[selectedChannel].transform.position.x, pV[selectedChannel] * 100);
                //Debug.DrawRay(new Vector2(-100, pV[selectedChannel] * 100),new Vector2(200,0),Color.red,1f);
            }
        }



        for (int i = 0; i < actualNumber; i++)
        {
            if (samples[i] < pV[i])
            {
                lV[i] = samples[i];
            }
        }
        //else if (hasUpwards) {

        /*hasUpwards = false;
         * flashValue = 2.5f;
         *
         * totalBeats++;
         * combo.text = totalBeats.ToString();*/
        // }

        /*if (samples[cP] < pPV)
         *  for (int i = 0; i < 2; i++) {
         *      if (pD[i] != pPD[i]) {
         *          Debug.Log("Working");
         *          pPV = 0;
         *
         *          flashValue = 2.5f;
         *          totalBeats++;
         *          combo.text = totalBeats.ToString();
         *      }
         *
         *      Debug.Log(pPD[i] + " " + pD[i]);
         *      pPD[i] = pD[i];
         *  }*/



        if (song.time >= 60 * currMinute)
        {
            Debug.LogWarning("Current BPM Tracked: " + bpmTracker);
            bpmTracker = 0;
            currMinute++;
        }

        pV = samples;

        //isPrevHigh = currPos;
    }
Ejemplo n.º 14
0
 void GetSpectrumAudioSource()
 {
     AudioListener.GetSpectrumData(samples, 0, FFTWindow.Blackman);
 }
Ejemplo n.º 15
0
 public void Update()
 {
     AudioListener.GetSpectrumData(Samples, Channel, FFTMode);
 }
Ejemplo n.º 16
0
        protected override void OnPopulateMesh(VertexHelper vertexHelper)
        {
            vertexHelper.Clear();
            AudioListener.GetSpectrumData(spectrum, 0, FFTWindow.Hanning);
            var outputF = AudioSettings.outputSampleRate;

            // 全binを初期化
            for (int i = 0; i < bins.Length; i++)
            {
                bins[i] = 0f;
            }

            var logMaxF  = Mathf.Log(graphMaxFrequency);            // 上のbinの周波数のlog
            var logMinF  = Mathf.Log(graphMinFrequency);
            var logRange = logMaxF - logMinF;

            if (logRange <= 0f)
            {
                logRange = 8f;
            }
            // まず周波数分類
            for (int i = 0; i < spectrum.Length; i++)
            {
                var f = outputF * 0.5f * (float)i / (float)spectrum.Length;
                if (f == 0f)
                {
                    f = float.Epsilon;
                }
                // 対数を取ってどのビンに入るか確定
                float binValue = (float)bins.Length * (Mathf.Log(f) - logMinF) / logRange;
                int   binIndex = Mathf.FloorToInt(binValue);
                if ((binIndex >= 0) && (binIndex < bins.Length))
                {
                    // そのビンにデータを加算
                    bins[binIndex] += spectrum[i];
                }
            }
            // 背景描画
            float rectH       = rectTransform.rect.height;
            float rectW       = rectTransform.rect.width;
            var   color       = new Color(0f, 0f, 0f, 0.5f);
            int   vertexCount = 0;

            vertexCount = Draw(0f, 0f, rectW, rectH, color, vertexHelper, vertexCount);

            // 横線描画。6dbごとに描画する。
            float maxDb   = graphMaxDb;
            float minDb   = graphMinDb;
            float dbRange = maxDb - minDb;

            if (dbRange <= 0f)
            {
                dbRange = 96f;
            }
            float hPerDb = rectH / dbRange;
            float yBase  = rectH * -minDb / dbRange;

            color = new Color(0x4a / 255f, 0x68 / 255f, 0x74 / 255f, 0.25f);
            float y = yBase + (6f * hPerDb);

            while (y < rectH)
            {
                vertexCount = Draw(0f, y - 1f, rectW, y + 1f, color, vertexHelper, vertexCount);
                y          += 6f * hPerDb;
            }
            y = yBase - (6f * hPerDb);
            while (y > 0f)
            {
                vertexCount = Draw(0f, y - 1f, rectW, y + 1f, color, vertexHelper, vertexCount);
                y          -= 6f * hPerDb;
            }
            // 0dbラインは濃く
            color.a     = 1f;
            vertexCount = Draw(0f, yBase - 1f, rectW, yBase + 1f, color, vertexHelper, vertexCount);

            // 縦線描画。
            float xBase   = rectW * (Mathf.Log(graphCenterFrequency) - logMinF) / logRange;
            float wOctave = rectW * Mathf.Log(2f) / logRange;

            color.a = 0.25f;
            float x = xBase + wOctave;

            while (x < rectW)
            {
                vertexCount = Draw(x - 1f, 0f, x + 1f, rectH, color, vertexHelper, vertexCount);
                x          += wOctave;
            }
            x = xBase - wOctave;
            while (x >= 0f)
            {
                vertexCount = Draw(x - 1f, 0f, x + 1f, rectH, color, vertexHelper, vertexCount);
                x          -= wOctave;
            }
            // 中央周波数は濃く
            color.a     = 1f;
            vertexCount = Draw(xBase - 1f, 0, xBase + 1f, rectH, color, vertexHelper, vertexCount);

            // ビンごとに描画
            float prevY = 0f;
            float barW  = rectTransform.rect.width / bins.Length;

            color = new Color(0x80 / 255f, 0x19 / 255f, 0x2d / 255f, 1f);
            for (int i = 0; i < bins.Length; i++)
            {
                var db = minDb;
                // 平均取る
                var v = bins[i];
                if (v > 0)
                {
                    db = Mathf.Log10(v) * 20f;
                    if (db < minDb)
                    {
                        db = minDb;
                    }
                }
                y = yBase * (db - minDb) / -minDb;
                if (v == 0f)                 // 0なら前の値につなげる
                {
                    y = prevY;
                }
                var x0 = barW * (float)i;
                var x1 = (barW * (float)(i + 1));
                vertexCount = DrawLine(x0, prevY, x1, y, color, vertexHelper, vertexCount);
                prevY       = y;
            }
        }
Ejemplo n.º 17
0
    // Update is called once per frame
    void Update()
    {
        AudioListener.GetSpectrumData(samples, 0, fftWindow);

        if (samples[frequency2] > spawnThershold2)
        {
            //print (samples[frequency2]);
            var mainSub = particleSys.main;
            mainSub.startColor = Color.black;
            mainSub.startSpeed = 3;
            //rb.AddForce(transform.forward * 100);
            //set the static var in the sprite script
            spriteSize.setSize = 10000;

            Instantiate(objectPrefab, new Vector3(8, 5, 0), transform.rotation);
        }


        if (samples[frequency3] > spawnThershold3)
        {
            //print (samples[frequency2]);
            var mainSub = particleSys.main;
            mainSub.startSpeed = 1;
            //rb.AddForce(transform.forward * 10);
            //set the static var in the sprite script
        }

        if ((samples[frequency2] > spawnThershold2) ^ (samples[frequency3] > spawnThershold3))
        {
            Instantiate(objectPrefab, new Vector3(0, 5, 0), transform.rotation);
        }



        if (samples[frequency] > spawnThershold)
        {
            //print (samples[frequency]);
            //rb.AddForce(transform.forward * 1000);
            var mainSub = particleSys.main;
            mainSub.startSpeed = 6;

            //create an object
            Instantiate(objectPrefab, new Vector3(-8, 5, 0), transform.rotation);

            //change particle color

            mainSub.startColor = Color.white;
        }



        int i = 0;

        for (i = 0; i < cutoffSample; i++)
        {
            Vector3 position = new Vector3(i * stepSize - size / 2.0f, samples[i] * amplitude, 0.0f);
            lineRenderer.SetPosition(i, position);
        }
        //  foreach (float sample in samples)
        //    {
        //        Vector3 position = new Vector3(i*stepSize-size/2.0f,sample*amplitude,0.0f);
        //        lineRenderer.SetPosition(i, position);
        //            i++;
        //    }
    }
Ejemplo n.º 18
0
    // Update is called once per frame
    void Update()
    {
        Time.timeScale = timeScale;
        if (timeScale < 1)
        {
            timeScale = timeScale + 0.1f;

            Time.fixedDeltaTime = 0.02F * Time.timeScale;
        }



        AudioListener.GetSpectrumData(samples, 0, fftWindow);

        if (samples[frequency2] > spawnThershold2)
        {
            print("freq1");
        }


        if (samples[frequency3] > spawnThershold3)
        {
            print("freq3");
        }

        if ((samples[frequency2] > spawnThershold2) ^ (samples[frequency3] > spawnThershold3))
        {
            print("freq2 + 3");
        }



        if (samples[frequency] > spawnThershold)
        {
            print("freq");
            timeScale = 0.1f;
            lightTimer++;

            if (lightTimer > 5)
            {
                if (lightToggle)
                {
                    lightSource.gameObject.SetActive(lightToggle);
                    lightToggle = false;
                    lightTimer  = 0;
                }
                else
                {
                    lightSource.gameObject.SetActive(lightToggle);
                    lightToggle = true;
                    lightTimer  = 0;
                }
            }


            enemies = GameObject.FindGameObjectsWithTag("Enemy");

            if (enemies.Length < 10)
            {
                int i = Random.Range(1, spawnPoints.Length);
                Instantiate(enemyPrefab, spawnPoints[i].transform.position, Quaternion.identity);
            }
            ;
        }
    }
Ejemplo n.º 19
0
    private void FixedUpdate()
    {
        //音源から現在の音量取得
        //GetOutputData()で音源の波形データを配列個数分取得。(周波数成分に分けていない総合的な波形データ)
        AudioListener.GetOutputData(_waveData, 1);
        var volume = _waveData.Select(x => x * x).Sum() / _waveData.Length;

        _noiseIntensityByVolume = volume / _aveVolume / 4; //曲中における現在の相対的な音量の大きさ。4で割っているのはいい感じのエフェクトにするための微調整。


        //音源から現在のピッチ取得
        //各周波成分で一番値が大きい=振幅が大きい=音量が大きいものを基音(ピッチ)とする。
        //16拍子 = 4小節ごとにピッチの見直し
        if (_beatCount % 16 == 0)
        {
            if (_doOnceInit)
            {
                _maxSpectrumValue = 0;
                _maxSpectrumIndex = 0;
                _doOnceInit       = false;
            }
            //サンプリングレートが44100Hzなので、実際の最大周波数は44100/2 Hz(ナイキスト周波数)
            //_spectrumの配列数が1024なので、44100/2/1024Hzごとに周波数成分を取得
            AudioListener.GetSpectrumData(_spectrum, 0, FFTWindow.Rectangular);
            for (int i = 0; i < _spectrum.Length; i++)
            {
                float val = _spectrum[i];
                if (val > _maxSpectrumValue)
                {
                    _maxSpectrumValue = val;
                    _maxSpectrumIndex = i;
                }
            }
        }
        else if (_beatCount % 16 == 8)
        {
            _doOnceInit = true;
        }
        //サンプリングレートが44100Hzなので、実際の最大周波数は44100/2 Hz(ナイキスト周波数)
        //_spectrumの配列数が1024なので、44100/2/1024Hzごとに周波数成分を取得
        //よって、一番音量が大きい周波数成分のピッチは、配列番号*44100/2/1024Hz
        var mainFreq = _maxSpectrumIndex * AudioSettings.outputSampleRate / 2 / _spectrum.Length;

        //BPMとピッチごとに色を変更
        if (musicController.bpm >= 140)
        {
            if (mainFreq >= 1046.502)
            {
                _material.SetColor("_Color", new Color(0f, 1f, 1f, 1f));
            }
            else if (mainFreq >= 739.989)
            {
                _material.SetColor("_Color", new Color(0f, 1f, 0.8f, 1f));
            }
            else if (mainFreq >= 523.251)
            {
                _material.SetColor("_Color", new Color(0f, 0.6f, 0.6f, 1f));
            }
            else if (mainFreq >= 369.994)
            {
                _material.SetColor("_Color", new Color(0f, 0.4f, 0.4f, 1f));
            }
            else if (mainFreq >= 261.626)
            {
                _material.SetColor("_Color", new Color(0f, 0.2f, 0.4f, 1f));
            }
            else
            {
                _material.SetColor("_Color", new Color(0f, 0.2f, 0.2f, 1f));
            }
        }
        else if (musicController.bpm >= 100)
        {
            if (mainFreq >= 1046.502)
            {
                _material.SetColor("_Color", new Color(1f, 1f, 0.8f, 1f));
            }
            else if (mainFreq >= 739.989)
            {
                _material.SetColor("_Color", new Color(1f, 0.8f, 0.4f, 1f));
            }
            else if (mainFreq >= 523.251)
            {
                _material.SetColor("_Color", new Color(1f, 0.6f, 0.2f, 1f));
            }
            else if (mainFreq >= 369.994)
            {
                _material.SetColor("_Color", new Color(1f, 0.6f, 0.6f, 1f));
            }
            else if (mainFreq >= 261.626)
            {
                _material.SetColor("_Color", new Color(1f, 0.4f, 0.6f, 1f));
            }
            else
            {
                _material.SetColor("_Color", new Color(1f, 0.4f, 1f, 1f));
            }
        }
        else
        {
            if (mainFreq >= 1046.502)
            {
                _material.SetColor("_Color", new Color(0.6f, 1f, 0.8f, 1f));
            }
            else if (mainFreq >= 739.989)
            {
                _material.SetColor("_Color", new Color(0.6f, 1f, 1f, 1f));
            }
            else if (mainFreq >= 523.251)
            {
                _material.SetColor("_Color", new Color(0.6f, 0.6f, 1f, 1f));
            }
            else if (mainFreq >= 369.994)
            {
                _material.SetColor("_Color", new Color(0.6f, 0.4f, 0.6f, 1f));
            }
            else if (mainFreq >= 261.626)
            {
                _material.SetColor("_Color", new Color(0.6f, 0.4f, 0.4f, 1f));
            }
            else
            {
                _material.SetColor("_Color", new Color(0.6f, 0.2f, 0.2f, 1f));
            }
        }

        /*
         * //周波数成分を10段階に分割し、オーディオスペクトラムを基にテクスチャにノイズを適用
         * for (var i = 0; i <= 103; i++)
         * {
         *  if (i == 103)
         *  {
         *      spectrumSum[0] = 0f;
         *  }
         *  else
         *  {
         *      spectrumSum[0] += _spectrum[i];
         *      int sign;
         *      if (Random.value <= 0.5f)
         *      {
         *          sign = -1;
         *      }
         *      else
         *      {
         *          sign = 1;
         *      }
         *      _material.SetFloat("_spectrum1", spectrumSum[0]/10 * sign);
         *  }
         * }
         * for (var i = 103; i <= 205; i++)
         * {
         *  if (i == 205)
         *  {
         *      spectrumSum[1] = 0f;
         *  }
         *  else
         *  {
         *      spectrumSum[1] += _spectrum[i];
         *      int sign;
         *      if (Random.value <= 0.5f)
         *      {
         *          sign = -1;
         *      }
         *      else
         *      {
         *          sign = 1;
         *      }
         *      _material.SetFloat("_spectrum2", spectrumSum[1]/10 * sign);
         *  }
         * }
         * for (var i = 205; i <= 308; i++)
         * {
         *  if (i == 308)
         *  {
         *      spectrumSum[2] = 0f;
         *  }
         *  else
         *  {
         *      spectrumSum[2] += _spectrum[i];
         *      int sign;
         *      if (Random.value <= 0.5f)
         *      {
         *          sign = -1;
         *      }
         *      else
         *      {
         *          sign = 1;
         *      }
         *      _material.SetFloat("_spectrum3", spectrumSum[2]/10 * sign);
         *  }
         * }
         * for (var i = 308; i <= 410; i++)
         * {
         *  if (i == 410)
         *  {
         *      spectrumSum[3] = 0f;
         *  }
         *  else
         *  {
         *      spectrumSum[3] += _spectrum[i];
         *      int sign;
         *      if (Random.value <= 0.5f)
         *      {
         *          sign = -1;
         *      }
         *      else
         *      {
         *          sign = 1;
         *      }
         *      _material.SetFloat("_spectrum4", spectrumSum[3]/10 * sign);
         *  }
         * }
         * for (var i = 410; i <= 512; i++)
         * {
         *  if (i == 512)
         *  {
         *      spectrumSum[4] = 0f;
         *  }
         *  else
         *  {
         *      spectrumSum[4] += _spectrum[i];
         *      int sign;
         *      if (Random.value <= 0.5f)
         *      {
         *          sign = -1;
         *      }
         *      else
         *      {
         *          sign = 1;
         *      }
         *      _material.SetFloat("_spectrum5", spectrumSum[4]/10 * sign);
         *  }
         * }
         * for (var i = 513; i <= 615; i++)
         * {
         *  if (i == 615)
         *  {
         *      spectrumSum[5] = 0f;
         *  }
         *  else
         *  {
         *      spectrumSum[5] += _spectrum[i];
         *      int sign;
         *      if (Random.value <= 0.5f)
         *      {
         *          sign = -1;
         *      }
         *      else
         *      {
         *          sign = 1;
         *      }
         *      _material.SetFloat("_spectrum6", spectrumSum[5]/10 * sign);
         *  }
         * }
         * for (var i = 615; i <= 717; i++)
         * {
         *  if (i == 717)
         *  {
         *      spectrumSum[6] = 0f;
         *  }
         *  else
         *  {
         *      spectrumSum[6] += _spectrum[i];
         *      int sign;
         *      if (Random.value <= 0.5f)
         *      {
         *          sign = -1;
         *      }
         *      else
         *      {
         *          sign = 1;
         *      }
         *      _material.SetFloat("_spectrum7", spectrumSum[6]/10 * sign);
         *  }
         * }
         * for (var i = 717; i <= 820; i++)
         * {
         *  if (i == 820)
         *  {
         *      spectrumSum[7] = 0f;
         *  }
         *  else
         *  {
         *      spectrumSum[7] += _spectrum[i];
         *      int sign;
         *      if (Random.value <= 0.5f)
         *      {
         *          sign = -1;
         *      }
         *      else
         *      {
         *          sign = 1;
         *      }
         *      _material.SetFloat("_spectrum8", spectrumSum[7]/10 * sign);
         *  }
         * }
         * for (var i = 820; i <= 922; i++)
         * {
         *  if (i == 922)
         *  {
         *      spectrumSum[8] = 0f;
         *  }
         *  else
         *  {
         *      spectrumSum[8] += _spectrum[i];
         *      int sign;
         *      if (Random.value <= 0.5f)
         *      {
         *          sign = -1;
         *      }
         *      else
         *      {
         *          sign = 1;
         *      }
         *      _material.SetFloat("_spectrum9", spectrumSum[8]/10 * sign);
         *  }
         * }
         * for (var i = 922; i <= 1024; i++)
         * {
         *  if (i == 1024)
         *  {
         *      spectrumSum[9] = 0f;
         *  }
         *  else
         *  {
         *      spectrumSum[9] += _spectrum[i];
         *      int sign;
         *      if (Random.value <= 0.5f)
         *      {
         *          sign = -1;
         *      }
         *      else
         *      {
         *          sign = 1;
         *      }
         *      _material.SetFloat("_spectrum10", spectrumSum[9]/10 * sign);
         *  }
         * }
         */

        //周波数成分を50段階に分割し、オーディオスペクトラムを基にテクスチャにノイズを適用
        //配列数1024/50==20.48
        //それぞれのfor内で初期化処理を実行するため、iの最大値を小数点切り上げ
        for (var i = 0; i <= 21; i++)
        {
            if (i == 21)
            {
                spectrumSum[0] = 0f;
            }
            else
            {
                spectrumSum[0] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum1", spectrumSum[0] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 21; i <= 41; i++)
        {
            if (i == 41)
            {
                spectrumSum[1] = 0f;
            }
            else
            {
                spectrumSum[1] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum2", spectrumSum[1] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 41; i <= 62; i++)
        {
            if (i == 62)
            {
                spectrumSum[2] = 0f;
            }
            else
            {
                spectrumSum[2] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum3", spectrumSum[2] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 62; i <= 82; i++)
        {
            if (i == 82)
            {
                spectrumSum[3] = 0f;
            }
            else
            {
                spectrumSum[3] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum4", spectrumSum[3] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 82; i <= 103; i++)
        {
            if (i == 103)
            {
                spectrumSum[4] = 0f;
            }
            else
            {
                spectrumSum[4] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum5", spectrumSum[4] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 103; i <= 123; i++)
        {
            if (i == 123)
            {
                spectrumSum[5] = 0f;
            }
            else
            {
                spectrumSum[5] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum6", spectrumSum[5] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 123; i <= 144; i++)
        {
            if (i == 144)
            {
                spectrumSum[6] = 0f;
            }
            else
            {
                spectrumSum[6] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum7", spectrumSum[6] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 144; i <= 164; i++)
        {
            if (i == 164)
            {
                spectrumSum[7] = 0f;
            }
            else
            {
                spectrumSum[7] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum8", spectrumSum[7] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 164; i <= 185; i++)
        {
            if (i == 185)
            {
                spectrumSum[8] = 0f;
            }
            else
            {
                spectrumSum[8] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum9", spectrumSum[8] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 185; i <= 205; i++)
        {
            if (i == 205)
            {
                spectrumSum[9] = 0f;
            }
            else
            {
                spectrumSum[9] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum10", spectrumSum[9] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 205; i <= 226; i++)
        {
            if (i == 226)
            {
                spectrumSum[10] = 0f;
            }
            else
            {
                spectrumSum[10] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum11", spectrumSum[10] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 226; i <= 246; i++)
        {
            if (i == 246)
            {
                spectrumSum[11] = 0f;
            }
            else
            {
                spectrumSum[11] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum12", spectrumSum[11] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 246; i <= 267; i++)
        {
            if (i == 267)
            {
                spectrumSum[12] = 0f;
            }
            else
            {
                spectrumSum[12] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum13", spectrumSum[12] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 267; i <= 287; i++)
        {
            if (i == 287)
            {
                spectrumSum[13] = 0f;
            }
            else
            {
                spectrumSum[13] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum14", spectrumSum[13] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 287; i <= 308; i++)
        {
            if (i == 308)
            {
                spectrumSum[14] = 0f;
            }
            else
            {
                spectrumSum[14] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum15", spectrumSum[14] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 308; i <= 328; i++)
        {
            if (i == 328)
            {
                spectrumSum[15] = 0f;
            }
            else
            {
                spectrumSum[15] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum16", spectrumSum[15] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 328; i <= 349; i++)
        {
            if (i == 349)
            {
                spectrumSum[16] = 0f;
            }
            else
            {
                spectrumSum[16] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum17", spectrumSum[16] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 349; i <= 369; i++)
        {
            if (i == 369)
            {
                spectrumSum[17] = 0f;
            }
            else
            {
                spectrumSum[17] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum18", spectrumSum[17] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 369; i <= 390; i++)
        {
            if (i == 390)
            {
                spectrumSum[18] = 0f;
            }
            else
            {
                spectrumSum[18] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum19", spectrumSum[18] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 390; i <= 410; i++)
        {
            if (i == 410)
            {
                spectrumSum[19] = 0f;
            }
            else
            {
                spectrumSum[19] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum20", spectrumSum[19] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 410; i <= 431; i++)
        {
            if (i == 431)
            {
                spectrumSum[20] = 0f;
            }
            else
            {
                spectrumSum[20] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum21", spectrumSum[20] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 431; i <= 451; i++)
        {
            if (i == 451)
            {
                spectrumSum[21] = 0f;
            }
            else
            {
                spectrumSum[21] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum22", spectrumSum[21] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 451; i <= 472; i++)
        {
            if (i == 472)
            {
                spectrumSum[22] = 0f;
            }
            else
            {
                spectrumSum[22] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum23", spectrumSum[22] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 472; i <= 492; i++)
        {
            if (i == 492)
            {
                spectrumSum[23] = 0f;
            }
            else
            {
                spectrumSum[23] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum24", spectrumSum[23] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 492; i <= 512; i++)
        {
            if (i == 512)
            {
                spectrumSum[24] = 0f;
            }
            else
            {
                spectrumSum[24] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum25", spectrumSum[24] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 512; i <= 533; i++)
        {
            if (i == 533)
            {
                spectrumSum[25] = 0f;
            }
            else
            {
                spectrumSum[25] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum26", spectrumSum[25] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 533; i <= 553; i++)
        {
            if (i == 553)
            {
                spectrumSum[26] = 0f;
            }
            else
            {
                spectrumSum[26] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum27", spectrumSum[26] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 553; i <= 574; i++)
        {
            if (i == 574)
            {
                spectrumSum[27] = 0f;
            }
            else
            {
                spectrumSum[27] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum28", spectrumSum[27] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 574; i <= 594; i++)
        {
            if (i == 594)
            {
                spectrumSum[28] = 0f;
            }
            else
            {
                spectrumSum[28] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum29", spectrumSum[28] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 594; i <= 615; i++)
        {
            if (i == 615)
            {
                spectrumSum[29] = 0f;
            }
            else
            {
                spectrumSum[29] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum30", spectrumSum[29] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 615; i <= 635; i++)
        {
            if (i == 635)
            {
                spectrumSum[30] = 0f;
            }
            else
            {
                spectrumSum[30] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum31", spectrumSum[30] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 635; i <= 656; i++)
        {
            if (i == 656)
            {
                spectrumSum[31] = 0f;
            }
            else
            {
                spectrumSum[31] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum32", spectrumSum[31] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 656; i <= 676; i++)
        {
            if (i == 676)
            {
                spectrumSum[32] = 0f;
            }
            else
            {
                spectrumSum[32] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum33", spectrumSum[32] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 676; i <= 697; i++)
        {
            if (i == 697)
            {
                spectrumSum[33] = 0f;
            }
            else
            {
                spectrumSum[33] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum34", spectrumSum[33] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 697; i <= 717; i++)
        {
            if (i == 717)
            {
                spectrumSum[34] = 0f;
            }
            else
            {
                spectrumSum[34] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum35", spectrumSum[34] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 717; i <= 738; i++)
        {
            if (i == 738)
            {
                spectrumSum[35] = 0f;
            }
            else
            {
                spectrumSum[35] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum36", spectrumSum[35] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 738; i <= 758; i++)
        {
            if (i == 758)
            {
                spectrumSum[36] = 0f;
            }
            else
            {
                spectrumSum[36] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum37", spectrumSum[36] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 758; i <= 779; i++)
        {
            if (i == 779)
            {
                spectrumSum[37] = 0f;
            }
            else
            {
                spectrumSum[37] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum38", spectrumSum[37] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 779; i <= 799; i++)
        {
            if (i == 799)
            {
                spectrumSum[38] = 0f;
            }
            else
            {
                spectrumSum[38] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum39", spectrumSum[38] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 799; i <= 820; i++)
        {
            if (i == 820)
            {
                spectrumSum[39] = 0f;
            }
            else
            {
                spectrumSum[39] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum40", spectrumSum[39] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 820; i <= 840; i++)
        {
            if (i == 840)
            {
                spectrumSum[40] = 0f;
            }
            else
            {
                spectrumSum[40] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum41", spectrumSum[40] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 840; i <= 861; i++)
        {
            if (i == 861)
            {
                spectrumSum[41] = 0f;
            }
            else
            {
                spectrumSum[41] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum42", spectrumSum[41] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 861; i <= 881; i++)
        {
            if (i == 881)
            {
                spectrumSum[42] = 0f;
            }
            else
            {
                spectrumSum[42] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum43", spectrumSum[42] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 881; i <= 902; i++)
        {
            if (i == 902)
            {
                spectrumSum[43] = 0f;
            }
            else
            {
                spectrumSum[43] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum44", spectrumSum[43] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 902; i <= 922; i++)
        {
            if (i == 922)
            {
                spectrumSum[44] = 0f;
            }
            else
            {
                spectrumSum[44] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum45", spectrumSum[44] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 922; i <= 943; i++)
        {
            if (i == 943)
            {
                spectrumSum[45] = 0f;
            }
            else
            {
                spectrumSum[45] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum46", spectrumSum[45] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 943; i <= 963; i++)
        {
            if (i == 963)
            {
                spectrumSum[46] = 0f;
            }
            else
            {
                spectrumSum[46] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum47", spectrumSum[46] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 963; i <= 984; i++)
        {
            if (i == 984)
            {
                spectrumSum[47] = 0f;
            }
            else
            {
                spectrumSum[47] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum48", spectrumSum[47] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 984; i <= 1004; i++)
        {
            if (i == 1004)
            {
                spectrumSum[48] = 0f;
            }
            else
            {
                spectrumSum[48] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum49", spectrumSum[48] * sign * _noiseIntensityByVolume);
            }
        }
        for (var i = 1004; i <= 1024; i++)
        {
            if (i == 1024)
            {
                spectrumSum[49] = 0f;
            }
            else
            {
                spectrumSum[49] += _spectrum[i];
                int sign;
                if (Random.value <= 0.5f)
                {
                    sign = -1;
                }
                else
                {
                    sign = 1;
                }
                _material.SetFloat("_spectrum50", spectrumSum[49] * sign * _noiseIntensityByVolume);
            }
        }



        if (audioSource.isPlaying)
        {
            //拍がくる時にalpha値を1にする。拍から次の拍までに徐々にalpha値を0→1にする。
            //拍と拍の間のどれくらいにきているかは、各拍が何秒ごとにきて、曲の経過秒とその倍数秒を比較(割った余り)すればOK
            //例えば、120bpmは120拍60秒なので、1拍0.5秒
            double currentRemainderBeatIntervalD = AudioSettings.dspTime % (60d / musicController.bpm);
            float  currentRemainderBeatIntervalF = (float)currentRemainderBeatIntervalD;
            //マシンの現実的な処理スピードを考慮して、_fpsBuffer(0.02秒)を設ける
            if (currentRemainderBeatIntervalD <= _fpsBuffer)
            {
                _material.SetFloat("_alpha", 1);
                if (_doOnceBeatCount)
                {
                    //拍数を数える
                    _beatCount      += 1;
                    _doOnceBeatCount = false;
                }
            }
            else
            {
                _material.SetFloat("_alpha", (1 - (currentRemainderBeatIntervalF / (60f / musicController.bpm))));
                _doOnceBeatCount = true;
            }
        }
        else
        {
            _material.SetFloat("_alpha", 0);
        }
    }
Ejemplo n.º 20
0
        private void LateUpdate()
        {
            if (audioSource && run)
            {
                // Check play time against previous play time
                if (audioSource.isPlaying && audioSource.time < prevTime)
                {
                    restart = true;
                }

                // Reinitialize the sample array if the sampleSize is changed
                if (sample.Length != sampleSize)
                {
                    sample = new float[sampleSize];
                }

                // AudioSource started playing
                if (audioSource.isPlaying && (audioSource.isPlaying != prevPlayState || restart))
                {
                    #if UNITY_WEBGL && !UNITY_EDITOR
                    WebGL_StartSampling(audioSource.GetInstanceID().ToString(), audioSource.clip.length, sampleSize, dataType.ToString());
                    #endif

                    prevPlayState = audioSource.isPlaying;
                    restart       = false;
                }

                // AudioSource is playing
                if (audioSource.isPlaying)
                {
                    #if UNITY_WEBGL && !UNITY_EDITOR
                    if (dataType == DataType.Amplitude)
                    {
                        // WebGL_GetAmplitude(audioSource.GetInstanceID().ToString(), sample, sampleSize);
                        WebGL_GetAmplitude(audioSource.GetInstanceID().ToString(), sample, sampleSize);
                    }
                    else // Frequency
                         // WebGL_GetFrequency(audioSource.GetInstanceID().ToString(), sample, sampleSize);
                    {
                        WebGL_GetFrequency(audioSource.GetInstanceID().ToString(), sample);
                    }
                    #else
                    if (dataType == DataType.Amplitude)
                    {
                        audioSource.GetOutputData(sample, 0);
                    }
                    else // Frequency
                    {
                        if (sample.Length == 32)
                        {
                            sample = new float[64];
                        }
                        AudioListener.GetSpectrumData(sample, 0, FFTWindow.BlackmanHarris);
                    }
                    #endif

                    if (sample != null)
                    {
                        // Average the sample
                        total = 0;
                        for (int i = 0; i < sampleSize; i++)
                        {
                            // Frequency is absolute values only
                            if (dataType == DataType.Frequency)
                            {
                                absoluteValues = true;
                            }

                            // Get the sample value
                            tempVal = sample[i];
                            // Get the original sign
                            sign = Mathf.Sign(tempVal);

                            if (absoluteValues) // Waveform or Frequency
                            {
                                if (dataType == DataType.Amplitude)
                                {
                                    // Get the absolute value
                                    tempVal = Mathf.Abs(tempVal);
                                    // Add boost
                                    tempVal = Mathf.Pow(tempVal, boostBase - boost);
                                    // Write boosted value back to the original sample
                                    sample[i] = tempVal;
                                }
                                else // Frequency
                                {
                                    #if UNITY_WEBGL && !UNITY_EDITOR
                                    freqBoost = ScaleRange(boost, 0f, 1f, freqBoostMin, freqBoostMax);
                                    freqBoost = freqBoost * -1;
                                    tempVal   = freqBoost / tempVal;
                                    tempVal   = Mathf.Clamp(tempVal, 0f, 1f);
                                    sample[i] = tempVal;
                                    #else
                                    // Add boost
                                    tempVal = Mathf.Pow(tempVal, boostBase - boost);
                                    // Write boosted value back to the original sample
                                    sample[i] = tempVal;
                                    #endif
                                }
                            }
                            else // Waveform not absolute
                            {
                                // Add boost
                                tempVal = Mathf.Pow(tempVal, boostBase - boost);
                                // Write the boosted and sign corrected value back to the original sample
                                sample[i] = tempVal * sign;
                            }

                            total += sample[i];
                        }
                        average = total / sampleSize;
                    }
                    else
                    {
                        Debug.Log("sample is null");
                    }

                    prevTime = audioSource.time;
                }

                // AudioSource stopped playing
                if (!audioSource.isPlaying && audioSource.isPlaying != prevPlayState)
                {
                    #if UNITY_WEBGL && !UNITY_EDITOR
                    WebGL_StopSampling(audioSource.GetInstanceID().ToString());
                    #endif

                    // clear values
                    for (int i = 0; i < sampleSize; i++)
                    {
                        sample[i] = 0;
                    }
                    average = 0;

                    prevPlayState = audioSource.isPlaying;
                    prevTime      = 0;
                }
            }
        }
Ejemplo n.º 21
0
 private void Update()
 {
     //rotate.localRotation = Quaternion.Euler(new Vector3(0,0,Time.time * 90));
     if (Input.GetKeyDown(KeyCode.S))
     {
         scalar -= 1f;
     }
     if (Input.GetKeyDown(KeyCode.W))
     {
         scalar += 1f;
     }
     AudioListener.GetSpectrumData(spectrum, 0, FFTWindow.Rectangular);
     for (int i = 0; i < spectrumMax.Length; i++)
     {
         squeezedSpectrum[i] = 0;
     }
     int[] quarts = { 23, 46, 92, 184 };
     for (int i = 0; i < spectrum.Length; i++)
     {
         int j = 1;
         if (i < quarts[0])
         {
             j = 1;
         }
         else if (i < quarts[1])
         {
             j = 2;
         }
         else if (i < quarts[2])
         {
             j = 3;
         }
         else if (i < quarts[3])
         {
             j = 4;
         }
         squeezedSpectrum[j - 1] += spectrum[i] * squeezedScalars[j - 1];
     }
     for (int i = 0; i < spectrumMax.Length; i++)
     {
         if (debug)
         {
             boxes[i].transform.localScale = new Vector3(2.5f, spectrumMax[i] * 2.5f * scalar, 1);
         }
         if (squeezedSpectrum[i] > spectrumMax[i])
         {
             spectrumMax[i] = squeezedSpectrum[i];
         }
         float squeezedScalarConst = 0.025f;
         if (squeezedSpectrum[i] * 2.5f * scalar > 10f)
         {
             squeezedScalars[i] -= 0.1f;
         }
         if (squeezedScalars[i] <= squeezedScalarConst)
         {
             squeezedScalars[i] = squeezedScalarConst * 30f;
         }
         //squeezedSpectrum[i] = 0;
     }
     //Debug.Log(transform.position.y);
     diff += Time.deltaTime * 1;
     //ball1.position = Vector3.Lerp(prev,goal,diff);
     //ball2.position = Vector3.Lerp(prev1, goal1, diff);
     ball1.localPosition += dir * Time.deltaTime * ballVel;
     ball1.localPosition  = new Vector3(Mathf.Clamp(ball1.localPosition.x, -4.5f, 4.5f), Mathf.Clamp(ball1.localPosition.y, -4.5f, 4.5f), 0);
     //ball1.localPosition = new Vector3(Mathf.Clamp(ball1.localPosition.x, -4.5f, 4.5f),ball1.localPosition.y);
     ball2.localPosition  = new Vector3(-ball1.localPosition.x, -ball1.localPosition.y, 0);
     ball3.localPosition  = new Vector3(ball1.localPosition.y, ball1.localPosition.x, 0);
     ball4.localPosition  = new Vector3(-ball1.localPosition.y, -ball1.localPosition.x, 0);
     ball2v.localPosition = ball1.localPosition;
     ball3v.localPosition = ball1.localPosition;
     ball4v.localPosition = ball1.localPosition;
     if (dir.x < goalDir.x)
     {
         dir.x += rotationalConst * Time.deltaTime;
         if (dir.x > goalDir.x)
         {
             dir.x = goalDir.x;
         }
     }
     else
     {
         dir.x -= rotationalConst * Time.deltaTime;
         if (dir.x < goalDir.x)
         {
             dir.x = goalDir.x;
         }
     }
     if (dir.y < goalDir.y)
     {
         dir.y += rotationalConst * Time.deltaTime;
         if (dir.y > goalDir.y)
         {
             dir.y = goalDir.y;
         }
     }
     else
     {
         dir.y -= rotationalConst * Time.deltaTime;
         if (dir.y < goalDir.y)
         {
             dir.y = goalDir.y;
         }
     }
 }
Ejemplo n.º 22
0
    void Update()
    {
        if (true) //Time.time - lastSample >= 0.043f)
        {
            // Set last sample time
            lastSample = Time.time;

            // Unity specific to pull out sample data, each array is filed with 1024 samples
            AudioListener.GetSpectrumData(leftData, 0, FFTWindow.BlackmanHarris);
            AudioListener.GetSpectrumData(rightData, 1, FFTWindow.BlackmanHarris);

            // Debug.Log(leftData[0]);

            /*
             * // Copy sample data into real (left) and imaginary parts (right)
             * for (int i = 0; i < leftData.Length; ++i)
             * {
             *  fftData[i].Re = leftData[i];
             *  fftData[i].Im = rightData[i];
             * }
             *
             * // Compute FFT on data (this FFT is correct, used it many times before)
             * Fourier.FFT(fftData, FourierDirection.Forward);
             */

            /*
             * for (int i = 256; i < fftData.Length; ++i)
             * {
             *  fftData[i].Re = 0f;
             *  fftData[i].Im = 0f;
             * }
             */

            // Compute the square module of FFT result
            for (int i = 0; i < fftData.Length; ++i)
            {
                // Real square
                float reSquare = fftData[i].Re * fftData[i].Re;

                // Imaginary square
                float imSquare = fftData[i].Im * fftData[i].Im;

                // Sum of squares + module
                module[i] = (imSquare + reSquare);

                // Meep
                module[i] = (leftData[i] * leftData[i]) + (rightData[i] * rightData[i]);
            }

            // Create a new energy array to store our 32 sub-bands in
            Es = new float[subBandSize];

            // Calculate samples per suband
            int samplesPerSubBand = fftData.Length / Es.Length;

            // Compute energy
            for (int i = 0; i < Es.Length; ++i)
            {
                Es[i] = 0;

                // This copies the output 0-31 into energy[0], 32-63 into energy[1], etc.
                for (int m = 0; m < samplesPerSubBand; ++m)
                {
                    Es[i] += module[(i * samplesPerSubBand) + m];
                }

                Es[i] /= samplesPerSubBand;
            }

            // This just shifts the previous energies array forward so we can set our new energy array at 0
            for (int i = (Ei.Length - 2); i >= 0; --i)
            {
                Ei[i + 1] = Ei[i];
            }

            // Write latest as first
            Ei[0] = Es;

            // Increase count by one
            count = Mathf.Min(count + 1, 43);

            // We need 43 samples to detect beats
            if (count == 43)
            {
                // Compute avarage energy of previous samples
                // this array is 32 wide (one for each subband)
                for (int i = 0; i < _Ei_.Length; ++i)
                {
                    // Clear current value from previous frame
                    _Ei_[i] = 0;

                    for (int n = 0; n < Ei.Length; ++n)
                    {
                        // Add it's energy for the sub-band i to the total
                        _Ei_[i] += Ei[n][i];
                    }

                    // We store 43 samples backwards
                    _Ei_[i] /= 43f;
                }

                for (int i = 0; i < Es.Length; ++i)
                {
                    // Debug.Log(string.Format("Es[{0}] = {1} and _Ei_[{0}] = {2}", i, Es[i], _Ei_[i]));
                    // Check if we have a beat by comparing Es[i] with 250 * _Ei_[i]
                    if (Es[i] > (4f * _Ei_[i]))
                    {
                        scales[i] = new Vector3(0.1f, 1f, 0.1f);
                    }
                    else
                    {
                        scales[i] = new Vector3(0.1f, 0.1f, 0.1f);
                    }
                }
            }
        }

        for (int i = 0; i < scales.Length; ++i)
        {
            Vector3 scale = subBands[i].transform.localScale;

            if (scales[i].y == 1f)
            {
                subBands[i].transform.localScale = scales[i];
            }
            else
            {
                subBands[i].transform.localScale = Vector3.Lerp(scale, scales[i], Time.deltaTime / 0.25f);
            }
        }
    }
Ejemplo n.º 23
0
 private void GetDataMusic( )
 {
     AudioListener.GetSpectrumData(_dataColumn, 0, FFTWindow.Rectangular);
 }
Ejemplo n.º 24
0
    /// <summary>
    /// This function updates this VisManager and runs the FFT on the target audio input,
    /// as well, it grabs the raw audio data.
    /// </summary>
    void Update()
    {
        //Check if the audio listener should be used
        if (m_bUseAudioListener)
        {
            //check if only the left or right channel was requested
            if (channel == VisManager.Channel.Left || channel == VisManager.Channel.Right)
            {
                //get the fft spectrum and raw audio data
                AudioListener.GetSpectrumData(m_afSpectrumData, (int)channel, windowType);
                AudioListener.GetOutputData(m_afRawAudioData, (int)channel);
            }
            //both channels were requested
            else
            {
                //get the fft spectrum data, from left and right channels, and merge the result
                AudioListener.GetSpectrumData(m_afSpectrumData, 0, windowType);
                AudioListener.GetSpectrumData(m_afAuxiliaryData, 1, windowType);
                for (int i = 0; i < (int)windowSize; i++)
                {
                    if (channel == VisManager.Channel.Average)
                    {
                        m_afSpectrumData[i] = (m_afSpectrumData[i] + m_afAuxiliaryData[i]) * 0.5f;
                    }
                    else if (channel == VisManager.Channel.Min)
                    {
                        m_afSpectrumData[i] = Mathf.Min(m_afSpectrumData[i], m_afAuxiliaryData[i]);
                    }
                    else if (channel == VisManager.Channel.Max)
                    {
                        m_afSpectrumData[i] = Mathf.Max(m_afSpectrumData[i], m_afAuxiliaryData[i]);
                    }
                }

                //get the raw audio data, from left and right channels, and merge the result
                AudioListener.GetOutputData(m_afRawAudioData, 0);
                AudioListener.GetOutputData(m_afAuxiliaryData, 1);
                for (int i = 0; i < (int)windowSize; i++)
                {
                    if (channel == VisManager.Channel.Average)
                    {
                        m_afRawAudioData[i] = (m_afRawAudioData[i] + m_afAuxiliaryData[i]) * 0.5f;
                    }
                    else if (channel == VisManager.Channel.Min)
                    {
                        if (Mathf.Abs(m_afAuxiliaryData[i]) < Mathf.Abs(m_afRawAudioData[i]))
                        {
                            m_afRawAudioData[i] = m_afAuxiliaryData[i];
                        }
                    }
                    else if (channel == VisManager.Channel.Max)
                    {
                        if (Mathf.Abs(m_afAuxiliaryData[i]) > Mathf.Abs(m_afRawAudioData[i]))
                        {
                            m_afRawAudioData[i] = m_afAuxiliaryData[i];
                        }
                    }
                }
            }
        }
        //Check if there is an audio source set to this VisManager
        else if (audioSource != null)
        {
            //check if only the left or right channel was requested
            if (channel == VisManager.Channel.Left || channel == VisManager.Channel.Right)
            {
                //get the fft spectrum and raw audio data
                audioSource.GetSpectrumData(m_afSpectrumData, (int)channel, windowType);
                audioSource.GetOutputData(m_afRawAudioData, (int)channel);
            }
            //both channels were requested
            else
            {
                //get the fft spectrum data, from left and right channels, and merge the result
                audioSource.GetSpectrumData(m_afSpectrumData, 0, windowType);
                audioSource.GetSpectrumData(m_afAuxiliaryData, 1, windowType);
                for (int i = 0; i < (int)windowSize; i++)
                {
                    if (channel == VisManager.Channel.Average)
                    {
                        m_afSpectrumData[i] = (m_afSpectrumData[i] + m_afAuxiliaryData[i]) * 0.5f;
                    }
                    else if (channel == VisManager.Channel.Min)
                    {
                        m_afSpectrumData[i] = Mathf.Min(m_afSpectrumData[i], m_afAuxiliaryData[i]);
                    }
                    else if (channel == VisManager.Channel.Max)
                    {
                        m_afSpectrumData[i] = Mathf.Max(m_afSpectrumData[i], m_afAuxiliaryData[i]);
                    }
                }

                //get the raw audio data, from left and right channels, and merge the result
                audioSource.GetOutputData(m_afRawAudioData, 0);
                audioSource.GetOutputData(m_afAuxiliaryData, 1);
                for (int i = 0; i < (int)windowSize; i++)
                {
                    if (channel == VisManager.Channel.Average)
                    {
                        m_afRawAudioData[i] = (m_afRawAudioData[i] + m_afAuxiliaryData[i]) * 0.5f;
                    }
                    else if (channel == VisManager.Channel.Min)
                    {
                        if (Mathf.Abs(m_afAuxiliaryData[i]) < Mathf.Abs(m_afRawAudioData[i]))
                        {
                            m_afRawAudioData[i] = m_afAuxiliaryData[i];
                        }
                    }
                    else if (channel == VisManager.Channel.Max)
                    {
                        if (Mathf.Abs(m_afAuxiliaryData[i]) > Mathf.Abs(m_afRawAudioData[i]))
                        {
                            m_afRawAudioData[i] = m_afAuxiliaryData[i];
                        }
                    }
                }
            }
        }

        //update the max debug value
        if (displaySpectrumDebug && debugTexture != null)
        {
            m_fMaxDebugValue -= 0.05f * Time.deltaTime;
            if (m_fMaxDebugValue < 0.1f)
            {
                m_fMaxDebugValue = 0.1f;
            }
        }
    }
Ejemplo n.º 25
0
    // Draw
    public override void Draw()
    {
        using (new GUIVerticalCenter()) {
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            GUILayout.BeginVertical("box");

            // 1st line: Track name
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (currentTrack != null)
            {
                GUILayout.Label(currentTrack.audioClip.name, trackNameStyle);
            }
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            // 2nd line: Controls
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();

            if (paused)
            {
                if (GUIHelper.Button(new GUIContent(playIcon)))
                {
                    currentAudioSource.Play();
                    paused = false;
                }
            }
            else
            {
                if (GUIHelper.Button(new GUIContent(pauseIcon)))
                {
                    currentAudioSource.Pause();
                    paused = true;
                }
            }

            if (GUIHelper.Button(new GUIContent(skipIcon)))
            {
                PlayNextClip();
            }

            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            GUILayout.EndVertical();
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            // 3rd line: Spectrum
            using (new GUIHorizontalCenter()) {
                using (new GUIHorizontal("box")) {
                    AudioListener.GetSpectrumData(rawSpectrum, 0, FFTWindow.BlackmanHarris);
                    ConvertRawSpectrumToBandLevels();

                    float multiplier = 512.0f;
                    int   maxHeight  = 128;
                    int   height;

                    for (int i = 0; i < meter.Length; i++)
                    {
                        meter[i] = Mathf.Max(meter[i] * Mathf.Exp(-10.0f * Time.deltaTime), bandLevels[i]);
                        height   = (int)(meter[i] * multiplier);

                        if (height > maxHeight)
                        {
                            height = maxHeight;
                        }

                        GUILayout.BeginVertical();
                        GUILayout.Space(maxHeight - height);
                        GUILayout.Box("", spectrumBandLevelStyle, GUILayout.Height(height));
                        GUILayout.EndVertical();
                        //GUILayout.Space(1);
                    }
                }
            }
        }
    }
Ejemplo n.º 26
0
 // Update is called once per frame
 void Update()
 {
     AudioListener.GetSpectrumData(spectrumAnalysis, 0, FFTWindow.BlackmanHarris);
 }