Пример #1
0
        private void PaintValues()
        {
            LookSpeedSlider.value = ConfigState.Instance.LookSpeed;
            LookYToggle.isOn      = ConfigState.Instance.LookInvert;

            GraphicsQualitySlider.maxValue     = QualitySettings.names.Length - 1;
            GraphicsQualitySlider.value        = QualitySettings.GetQualityLevel();
            GraphicsQualitySlider.interactable = true;

            AntialiasingQualitySlider.value = ConfigState.Instance.AntialiasingQuality;
            ViewDistanceSlider.value        = ConfigState.Instance.ViewDistance;

            SoundVolumeSlider.value = ConfigState.Instance.SoundVolume;
            MusicVolumeSlider.value = ConfigState.Instance.MusicVolume;

            var cList = new List <string>(Enum.GetNames(typeof(AudioSpeakerMode)));

            ChannelDropdown.ClearOptions();
            ChannelDropdown.AddOptions(cList);
            ChannelDropdown.value = cList.IndexOf(AudioSettings.GetConfiguration().speakerMode.ToString());

            var iList = MappedInput.AvailableMappers.ToList();

            InputDropdown.ClearOptions();
            InputDropdown.AddOptions(iList);
            InputDropdown.value = iList.IndexOf(ConfigState.Instance.InputMapper);

            //handle subpanels
            foreach (var subpanel in PanelContainer.GetComponentsInChildren <ConfigSubpanelController>())
            {
                subpanel.PaintValues();
            }
        }
    /// Initializes the audio system with the current audio configuration.
    /// @note This should only be called from the main Unity thread.
    public static void Initialize(GvrAudioListener listener, Quality quality)
    {
        if (!initialized)
        {
#if !UNITY_EDITOR && UNITY_ANDROID
            SetApplicationState();
#endif
            // Initialize the audio system.
            AudioConfiguration config = AudioSettings.GetConfiguration();
            sampleRate      = config.sampleRate;
            numChannels     = (int)config.speakerMode;
            framesPerBuffer = config.dspBufferSize;
            if (numChannels != (int)AudioSpeakerMode.Stereo)
            {
                Debug.LogError("Only 'Stereo' speaker mode is supported by GVR Audio.");
                return;
            }
            Initialize(quality, sampleRate, numChannels, framesPerBuffer);
            listenerTransform = listener.transform;

            initialized = true;
        }
        else if (listener.transform != listenerTransform)
        {
            Debug.LogError("Only one GvrAudioListener component is allowed in the scene.");
            GvrAudioListener.Destroy(listener);
        }
    }
Пример #3
0
        void Update()
        {
            if (target.clip == null)
            {
                if (lines.Count > 0)
                {
                    ResetLines(0);
                }
                clip = null;
                return;
            }

            if (clip != target.clip)
            {
                clip = target.clip;
                int channelCount    = clip.channels;
                var conf            = AudioSettings.GetConfiguration();
                int maxChannelCount = SpeakerModeToChannel[conf.speakerMode];
                channelCount = Math.Min(channelCount, maxChannelCount);
                ResetLines(channelCount);
            }
            for (int lineIndex = 0; lineIndex < lines.Count; lineIndex++)
            {
                target.GetSpectrumData(spectrum, lineIndex, FFTWindow.Rectangular);
                for (int i = 1; i < array.Length; i++)
                {
                    float x = rectTransform.rect.width * i / array.Length * xRatio;
                    float y = rectTransform.rect.height * Mathf.Log(spectrum[i] + 1) * yRatio;
                    array[i] = new Vector3(x, y, 0);
                }
                lines[lineIndex].SetPositions(array);
            }
        }
Пример #4
0
        void OnAudioConfigurationChanged(bool deviceChanged)
        {
            var conf  = AudioSettings.GetConfiguration();
            int count = AudioSettingsUtility.SpeakerModeToChannel(conf.speakerMode);

            ResetLines(count);
        }
Пример #5
0
        public void ClAppErrorReport(string message, string stackTrace, bool isException, RpcCallback callback)
        {
            var audioConfig = AudioSettings.GetConfiguration();

            Rpc("ClAppErrorReport", new JsonObj()
            {
                ["version"] = Application.version,

                ["message"]   = message,
                ["stack"]     = stackTrace,
                ["exception"] = isException,
                //["source"] = error.Source,

                ["platform"] = GetPlatform(),
                ["runtime"]  = Application.platform.ToString().ToLower(),

                ["sampleRate"] = audioConfig.sampleRate,
                ["bufferSize"] = audioConfig.dspBufferSize,

                ["model"] = SystemInfo.deviceModel,
                ["name"]  = SystemInfo.deviceName,
                ["os"]    = SystemInfo.operatingSystem,
                ["cpu"]   = SystemInfo.processorType,
                ["gpu"]   = SystemInfo.graphicsDeviceType,
            }, callback);
        }
        // Returns true, if everything is done:
        private bool ManageAudioSettings()
        {
            bool allDone = true;

            EditorGUILayout.BeginHorizontal();

            EditorGUILayout.LabelField("Speaker Mode", EditorStyles.label, GUILayout.MaxWidth(_leftLabelMaxWidth));

            AudioConfiguration audioConfig = AudioSettings.GetConfiguration();

            if (audioConfig.speakerMode == AudioSpeakerMode.Mode5point1)
            {
                EditorGUILayout.LabelField("(Surround 5.1)", EditorStyles.label);
            }
            else
            {
                allDone = false;

                if (GUILayout.Button("Set to Surround 5.1"))
                {
                    SetupSurroundSound();
                }
            }

            EditorGUILayout.EndHorizontal();

            return(allDone);
        }
    /// Initializes the audio system with the current audio configuration.
    /// @note This should only be called from the main Unity thread.
    public static void Initialize(CardboardAudioListener listener, Quality quality)
    {
        if (!initialized)
        {
            // Initialize the audio system.
#if UNITY_4_5 || UNITY_4_6 || UNITY_4_7
            sampleRate  = AudioSettings.outputSampleRate;
            numChannels = (int)AudioSettings.speakerMode;
            int numBuffers = -1;
            AudioSettings.GetDSPBufferSize(out framesPerBuffer, out numBuffers);
#else
            AudioConfiguration config = AudioSettings.GetConfiguration();
            sampleRate      = config.sampleRate;
            numChannels     = (int)config.speakerMode;
            framesPerBuffer = config.dspBufferSize;
#endif
            if (numChannels != (int)AudioSpeakerMode.Stereo)
            {
                Debug.LogError("Only 'Stereo' speaker mode is supported by Cardboard.");
                return;
            }
            Initialize(quality, sampleRate, numChannels, framesPerBuffer);
            listenerTransform = listener.transform;
            initialized       = true;

            Debug.Log("Cardboard audio system is initialized (Quality: " + quality + ", Sample Rate: " +
                      sampleRate + ", Channels: " + numChannels + ", Frames Per Buffer: " +
                      framesPerBuffer + ").");
        }
        else if (listener.transform != listenerTransform)
        {
            Debug.LogError("Only one CardboardAudioListener component is allowed in the scene.");
            //CardboardAudioListener.Destroy(listener);
        }
    }
Пример #8
0
    //TODO Current changing AudioMode in runtime make crash sound. Waiting for fixed this by Unity team.
    /// <summary>
    /// Sets the general audio mode.
    /// </summary>
    /// <param name="value">Value of audio speaker mode.</param>
    public static void SetGeneralAudioMode(int value)
    {
        AudioConfiguration config = AudioSettings.GetConfiguration();

        switch (value)
        {
        case 1:
            config.speakerMode = AudioSpeakerMode.Mono;
            break;

        case 2:
            config.speakerMode = AudioSpeakerMode.Stereo;
            break;

        case 3:
            config.speakerMode = AudioSpeakerMode.Quad;
            break;

        case 4:
            config.speakerMode = AudioSpeakerMode.Surround;
            break;

        case 5:
            config.speakerMode = AudioSpeakerMode.Mode5point1;
            break;

        case 6:
            config.speakerMode = AudioSpeakerMode.Mode7point1;
            break;
        }

        AudioSettings.Reset(config);
    }
Пример #9
0
    // public AudioSource c;

    // Use this for initialization
    void Start()
    {
        AudioConfiguration audio_config = AudioSettings.GetConfiguration();

        AudioSettings.Reset(audio_config);
        //  this.c.Play();
    }
    /// <summary>
    /// Call this function to create geometry handle
    /// </summary>
    void CreatePropagationGeometry()
    {
        AudioConfiguration config = AudioSettings.GetConfiguration();

        // Create Geometry
        if (PropIFace.CreateAudioGeometry(out geometryHandle) != OSPSuccess)
        {
            throw new Exception("Unable to create geometry handle");
        }

        // Upload Mesh
        if (filePath != null && filePath.Length != 0 && fileEnabled && Application.isPlaying)
        {
            if (!ReadFile())
            {
                Debug.Log("Failed to read file, attempting to regenerate audio geometry");

                // We should not try to upload data dynamically if data already exists
                UploadGeometry();
            }
        }
        else
        {
            UploadGeometry();
        }
    }
Пример #11
0
        private void Awake()
        {
            if (Instance != null)
            {
                throw new Exception("You should only have 1 AudioSystem in your game! " + name);
            }
            Instance = this;

            //NOTE When running tests you cannot use DontDestroyOnLoad in editor mode
            if (transform.parent == null && Application.isPlaying)
            {
                DontDestroyOnLoad(this);
            }

            // Reset transform
            transform.position   = Vector3.zero;
            transform.rotation   = Quaternion.identity;
            transform.localScale = Vector3.one;

            // Setup new channel pool
            var config = AudioSettings.GetConfiguration();

            channels = new List <AudioSource>(config.numRealVoices);
            for (var i = 0; i < channels.Capacity; ++i)
            {
                channels.Add(CreateChannel(i));
            }
        }
Пример #12
0
    public void changeGlobalVolume(Slider slider)
    {
        AudioConfiguration config = AudioSettings.GetConfiguration();

        config.dspBufferSize = (int)slider.value;
        AudioSettings.Reset(config);
    }
Пример #13
0
        /// <summary>
        /// Starts microphone capture on the first available microphone.
        /// </summary>
        /// <returns>True if a microphone was available to capture, otherwise false.</returns>
        public bool StartMicrophone()
        {
            if (microphoneAudioSource == null)
            {
                Debug.LogWarning("No AudioSource for microphone audio was specified");
                return(false);
            }

            if (Microphone.devices.Length == 0)
            {
                Debug.LogWarning("No connected microphones detected");
                return(false);
            }

            int minFreq, maxFreq, reqFreq;

            Microphone.GetDeviceCaps(Microphone.devices[0], out minFreq, out maxFreq);
            reqFreq = Mathf.Clamp(DefaultMicrophoneFreq, minFreq, maxFreq);
            microphoneAudioSource.clip = Microphone.Start(Microphone.devices[0], true, 1, reqFreq);
            microphoneAudioSource.loop = true;

            // don't start playing the AudioSource until we have some data (else we get a weird doubleling of audio)
            StartCoroutine(StartAudioSourceCoroutine());

            AudioConfiguration currentConfiguration = AudioSettings.GetConfiguration();

            tickTime = (float)currentConfiguration.dspBufferSize / currentConfiguration.sampleRate;

            isInitialized = true;

            return(true);
        }
Пример #14
0
        private void PaintValues()
        {
            InputMappers = MappedInput.AvailableMappers.ToList();
            InputDropdown.ClearOptions();
            InputDropdown.AddOptions(InputMappers.Select(m => Sub.Replace(m, "CFG_MAPPERS")).ToList());
            int iIndex = InputMappers.IndexOf(ConfigState.Instance.InputMapper);

            InputDropdown.value = iIndex >= 0 ? iIndex : 0;
            ConfigureInputButton.interactable = iIndex >= 0; //enable configure button

            LookSpeedSlider.value = ConfigState.Instance.LookSpeed;
            LookYToggle.isOn      = ConfigState.Instance.LookInvert;

            //Resolutions = new List<Resolution>(Screen.resolutions);
            Resolutions = GetDeduplicatedResolutionList(Screen.resolutions);
            ResolutionDropdown.ClearOptions();
            ResolutionDropdown.AddOptions(Resolutions.Select(r => $"{r.x} x {r.y}").ToList());
            int rIndex = Resolutions.IndexOf(ConfigState.Instance.Resolution);

            ResolutionDropdown.value = rIndex > 0 ? rIndex : Resolutions.Count - 1;

            FullscreenToggle.isOn = ConfigState.Instance.FullScreen;
            FramerateSlider.value = Math.Max(0, ConfigState.Instance.MaxFrames);
            VsyncSlider.value     = ConfigState.Instance.VsyncCount;

            GraphicsQualitySlider.maxValue     = QualitySettings.names.Length - 1;
            GraphicsQualitySlider.value        = QualitySettings.GetQualityLevel();
            GraphicsQualitySlider.interactable = true;

            AntialiasingQualitySlider.value = ConfigState.Instance.AntialiasingQuality;
            ViewDistanceSlider.value        = ConfigState.Instance.ViewDistance;
            FovSlider.value         = Mathf.RoundToInt(ConfigState.Instance.FieldOfView);
            EffectDwellSlider.value = Mathf.RoundToInt(ConfigState.Instance.EffectDwellTime);

            ShowFpsToggle.isOn = ConfigState.Instance.ShowFps;

            SoundVolumeSlider.value = ConfigState.Instance.SoundVolume;
            MusicVolumeSlider.value = ConfigState.Instance.MusicVolume;

            var cList = new List <string>(Enum.GetNames(typeof(AudioSpeakerMode)));

            ChannelDropdown.ClearOptions();
            ChannelDropdown.AddOptions(cList);
            ChannelDropdown.value = cList.IndexOf(AudioSettings.GetConfiguration().speakerMode.ToString());


            //handle subpanels
            foreach (var subpanel in PanelContainer.GetComponentsInChildren <ConfigSubpanelController>())
            {
                try
                {
                    subpanel.PaintValues();
                }
                catch (Exception e)
                {
                    Debug.LogError($"Failed to paint values for subpanel \"{subpanel.name}\"");
                    Debug.LogException(e);
                }
            }
        }
Пример #15
0
        /// <summary>
        /// Apply the current ConfigState configuration to the game
        /// </summary>
        public void ApplyConfiguration()
        {
            //AUDIO CONFIG
            AudioListener.volume = ConfigState.Instance.SoundVolume;
            var ac = AudioSettings.GetConfiguration();

#if UNITY_WSA
            if (ConfigState.Instance.SpeakerMode == AudioSpeakerMode.Raw)
            {
                ConfigState.Instance.SpeakerMode = AudioSpeakerMode.Stereo;
            }
#endif
            ac.speakerMode = ConfigState.Instance.SpeakerMode;
            AudioSettings.Reset(ac);

            //VIDEO CONFIG
            if (ConfigState.Instance.UseCustomVideoSettings)
            {
                ApplyExtendedGraphicsConfiguration();
            }

            if (!CoreParams.IsEditor)
            {
                Screen.SetResolution(ConfigState.Instance.Resolution.x, ConfigState.Instance.Resolution.y, ConfigState.Instance.FullScreen, ConfigState.Instance.RefreshRate);
            }

            QualitySettings.vSyncCount  = ConfigState.Instance.VsyncCount;
            Application.targetFrameRate = ConfigState.Instance.MaxFrames;

            //INPUT CONFIG
            MappedInput.SetMapper(ConfigState.Instance.InputMapper); //safe?

            //let other things handle it on their own
            QdmsMessageBus.Instance.PushBroadcast(new ConfigChangedMessage());
        }
    private void Start()
    {
        var config = AudioSettings.GetConfiguration();

        config.numRealVoices = maxCount;
        AudioSettings.Reset(config);
    }
Пример #17
0
    void setupAudioBuffer()
    {
        AudioConfiguration config = AudioSettings.GetConfiguration();

        switch (PlayerPrefs.GetInt("audioQuality"))
        {
        case 0:
            config.dspBufferSize = 256;
            break;

        case 1:
            config.dspBufferSize = 512;
            break;

        case 2:
            config.dspBufferSize = 1024;
            break;

        default:
            break;
        }

        AudioSource[] sources = FindObjectsOfType <AudioSource>();
        for (int i = 0; i < sources.Length; i++)
        {
            sources[i].enabled = false;
        }
        AudioSettings.Reset(config);
        for (int i = 0; i < sources.Length; i++)
        {
            sources[i].enabled = true;
        }
    }
Пример #18
0
    //private FileStream fileStream;

    void Awake()
    {
        outputRate = AudioSettings.GetConfiguration().sampleRate;
        // the following is deprecated and causes the sound system to reset
        // essentially yielding no audio whatsover (unity 2018)
        //AudioSettings.outputSampleRate = outputRate;
    }
        private void SetupSurroundSound()
        {
            AudioConfiguration audioConfig = AudioSettings.GetConfiguration();

            audioConfig.speakerMode = AudioSpeakerMode.Mode5point1;
            AudioSettings.Reset(audioConfig);
        }
Пример #20
0
    IEnumerator InitMicCoroutine()
    {
        var audioConfig = AudioSettings.GetConfiguration();

        string microphoneDevice = Microphone.devices[0];

        Debug.Log("Microphones:");
        foreach (var device in Microphone.devices)
        {
            Debug.Log("- " + device);
        }
        Debug.Log("Selected device: " + microphoneDevice);

        _MicrophoneClip = Microphone.Start(microphoneDevice, true, 1, audioConfig.sampleRate);
        while (!(Microphone.GetPosition(microphoneDevice) > 0))
        {
        }
        int micPos = Microphone.GetPosition(null);

        Debug.Log("Start Mic(pos): " + micPos);

        using (var block = _Graph.CreateCommandBlock())
        {
            block.UpdateAudioKernel <MicrophoneNodePlayKernel, MicrophoneNode.Parameters, MicrophoneNode.Providers, MicrophoneNode>(new MicrophoneNodePlayKernel(micPos), _Microphone);
        }

        yield return(null);
    }
Пример #21
0
    ////////////////////////////////////////////////////////////////
    public void Start()
    {
        var audio_configuration = AudioSettings.GetConfiguration();

        audio_configuration.dspBufferSize = 512;
        AudioSettings.Reset(audio_configuration);

        m_InstanceID = NewInstance(audio_configuration.sampleRate);
        _EnableCompletedVoicePolling(true, m_InstanceID);

        var dummy = AudioClip.Create("dummy", 1, 1, AudioSettings.outputSampleRate, false);

        dummy.SetData(new float[] { 1 }, 0);

        AudioSource TargetSrc = GetComponent <AudioSource>();

        TargetSrc.clip         = dummy;
        TargetSrc.loop         = true;
        TargetSrc.spatialBlend = 1;
        TargetSrc.Play();

        m_bRunning = true;

        if (m_sTextToParse.Length > 0)
        {
            ParseString(m_sTextToParse);
            m_sTextToParse = "";
        }
    }
Пример #22
0
    private static void UpdateDSPBufferSize()
    {
        var config = AudioSettings.GetConfiguration();

        config.dspBufferSize = (int)Math.Pow(2, Settings.Instance.DSPBufferSize);
        AudioSettings.Reset(config);
    }
        public void Start()
        {
            #if UNITY_STANDALONE_OSX
            _core = new Core(OS.OSX, CorePath, SystemDirectory);
            #else
            _core = new Core(OS.Windows, CorePath, SystemDirectory);
            #endif

            _core.AudioSampleBatchHandler += audioSampleBatchHandler;
            _core.LogHandler        += logHandler;
            _core.VideoFrameHandler += videoFrameHandler;

            _core.Load(ROMPath);

            Time.fixedDeltaTime = (float)1 / (float)_core.FrameRate;

            AudioConfiguration audioConfiguration = AudioSettings.GetConfiguration();
            audioConfiguration.sampleRate = (int)_core.AudioSampleRate;
            AudioSettings.Reset(audioConfiguration);

            // this is required for OnAudioFilterRead to work and needs to be done after setting the AudioSettings.outputSampleRate
            gameObject.AddComponent <AudioSource>();

            _core.StartFrameTiming();
        }
    // Use this for initialization
    void Start()
    {
        AudioConfiguration config = AudioSettings.GetConfiguration();

        config.numVirtualVoices = 6;
        config.numRealVoices    = 2;
        AudioSettings.Reset(config);

        controller = FindObjectOfType <FrameworkController>();
        source     = GetComponent <AudioSource>();

        if (controller != null)
        {
            source.Play();
        }
        else
        {
            Debug.Log("Framework controller not found. Are you starting from MainMenu Scene?");
        }

        SoundSlider.onValueChanged.AddListener(delegate {
            UpdatePriorities();
        });
        NoiseSlider.onValueChanged.AddListener(delegate {
            UpdatePriorities();
        });

        UpdatePriorities();
        PlayAll();
    }
Пример #25
0
    void OnGUI()
    {
        //storing the audio source in source
        AudioSource source   = GetComponent <AudioSource>();
        bool        modified = false;

        AudioConfiguration config = AudioSettings.GetConfiguration();

        //reconfiguring the values and appropraitely changing the modified values
        config.speakerMode      = (AudioSpeakerMode)GUIRow("speakerMode", validSpeakerModes, (int)config.speakerMode, ref modified);
        config.dspBufferSize    = GUIRow("dspBufferSize", validDSPBufferSizes, config.dspBufferSize, ref modified);
        config.sampleRate       = GUIRow("sampleRate", validSampleRates, config.sampleRate, ref modified);
        config.numRealVoices    = GUIRow("RealVoices", validNumRealVoices, config.numRealVoices, ref modified);
        config.numVirtualVoices = GUIRow("numVirtualVoices", validNumVirtualVoices, config.numVirtualVoices, ref modified);

        //we reset if the values have changed
        if (modified)
        {
            AudioSettings.Reset(config);
        }

        //when the button pressed the audio starts playing
        if (GUILayout.Button("Start"))
        {
            source.Play();
        }

        //audio stops playing on pressing the Stop
        if (GUILayout.Button("Stop"))
        {
            source.Stop();
        }
    }
Пример #26
0
    private void SetupMic()
    {
        // default device
        myMicDevice = "";
        // try to find one that matches identifier
        if (microphoneIdentifier != "")
        {
            foreach (string device in Microphone.devices)
            {
                if (device.Contains(microphoneIdentifier))
                {
                    myMicDevice = device;
                }
            }
        }

        // make a clip that loops recording when it reaches the end, is 10 seconds long, and uses the project sample rate
        micClip = Microphone.Start(myMicDevice, true, 10, AudioSettings.GetConfiguration().sampleRate);

        mySource.clip = micClip;
        // also loop the audio source
        mySource.loop = true;
        // high priority!
        mySource.priority = 0;
        // wait for mic to start
        while (!(Microphone.GetPosition(myMicDevice) > 0))
        {
        }
        ;
        // play audio source!
        mySource.Play();
    }
Пример #27
0
            public bool LoadGame(string gamePath)
            {
                GameInfo gameInfo = LoadGameInfo(gamePath);
                bool     ret      = Libretro.RetroLoadGame(ref gameInfo);

                Console.WriteLine("\nSystem information:");

                _av = new SystemAVInfo();
                Libretro.RetroGetSystemAVInfo(ref _av);

                var audioConfig = AudioSettings.GetConfiguration();

                audioConfig.sampleRate = (int)_av.timing.sample_rate;
                AudioSettings.Reset(audioConfig);

                Debug.Log("Geometry:");
                Debug.Log("Base width: " + _av.geometry.base_width);
                Debug.Log("Base height: " + _av.geometry.base_height);
                Debug.Log("Max width: " + _av.geometry.max_width);
                Debug.Log("Max height: " + _av.geometry.max_height);
                Debug.Log("Aspect ratio: " + _av.geometry.aspect_ratio);
                Debug.Log("Geometry:");
                Debug.Log("Target fps: " + _av.timing.fps);
                Debug.Log("Sample rate " + _av.timing.sample_rate);
                return(ret);
            }
Пример #28
0
 /// Initializes the audio system with the current audio configuration.
 /// @note This should only be called from the main Unity thread.
 public static void Initialize(GvrAudioListener listener, Quality quality)
 {
     if (!initialized)
     {
         // Initialize the audio system.
         AudioConfiguration config = AudioSettings.GetConfiguration();
         sampleRate      = config.sampleRate;
         numChannels     = (int)config.speakerMode;
         framesPerBuffer = config.dspBufferSize;
         if (numChannels != (int)AudioSpeakerMode.Stereo)
         {
             Debug.LogError("Only 'Stereo' speaker mode is supported by GVR Audio.");
             return;
         }
         if (Application.platform != RuntimePlatform.Android)
         {
             // TODO: GvrAudio bug on Android with Unity 2017
             Initialize((int)quality, sampleRate, numChannels, framesPerBuffer);
         }
         listenerTransform = listener.transform;
         if (Application.platform == RuntimePlatform.Android)
         {
             // TODO: GvrAudio bug on Android with Unity 2017
             return;
         }
         initialized = true;
     }
     else if (listener.transform != listenerTransform)
     {
         Debug.LogError("Only one GvrAudioListener component is allowed in the scene.");
         GvrAudioListener.Destroy(listener);
     }
 }
    /// Computes the RT60s and proxy room properties.
    /// @note This should only be called from the main Unity thread.
    public static bool ComputeRt60sAndProxyRoom(
        int totalNumPaths, int numPathsPerBatch, int maxDepth, float energyThreshold,
        Vector3 probePosition, float listenerSphereRadius, ref float[] outputRt60s,
        ref RoomProperties outputProxyRoomProperties)
    {
#if UNITY_EDITOR
        float[] probePositionFloatArray =
            new float[] { probePosition.x, probePosition.y, probePosition.z };
        IntPtr outputProxyRoomPropertiesPtr =
            Marshal.AllocHGlobal(Marshal.SizeOf(typeof(RoomProperties)));
        float sampleRate = (float)AudioSettings.GetConfiguration().sampleRate;
        int   impulseResponseNumSamples = (int)(maxReverbTime * sampleRate);
        if (!ComputeRt60sAndProxyRoom(totalNumPaths, numPathsPerBatch, maxDepth, energyThreshold,
                                      probePositionFloatArray, listenerSphereRadius, sampleRate,
                                      impulseResponseNumSamples, outputRt60s,
                                      outputProxyRoomPropertiesPtr))
        {
            return(false);
        }

        outputProxyRoomProperties = (RoomProperties)Marshal.PtrToStructure(
            outputProxyRoomPropertiesPtr, typeof(RoomProperties));
        Marshal.FreeHGlobal(outputProxyRoomPropertiesPtr);
        return(true);
#else
        return(false);
#endif  // UNITY_EDITOR
    }
Пример #30
0
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //	* Derived Method: Start
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    void Start()
    {
        // Set DSP Buffer Size
#if !UNITY_EDITOR && !UNITY_STANDALONE_WIN && !UNITY_STANDALONE_OSX
        var audioSettings = AudioSettings.GetConfiguration();
        audioSettings.dspBufferSize /= 2;
        AudioSettings.Reset(audioSettings);
#endif
        Instance = this;

        // Grab all Audio Sources already existing on this object
        sm_aAudioSource.Clear();
        AudioSource[] acquiredAudioSources = this.gameObject.GetComponents <AudioSource>();
        if (acquiredAudioSources.Length > m_iTotalAudioSourcesCount)
        {
            m_iTotalAudioSourcesCount = acquiredAudioSources.Length;
        }

        // Add Existing To List
        for (int i = 0; i < acquiredAudioSources.Length; ++i)
        {
            sm_aAudioSource.Add(new AudioHandlerManager(acquiredAudioSources[i]));
        }

        // Create the rest of the AudioSources up until the desired amount exist. Or stop if we already have more than required.
        for (int i = sm_aAudioSource.Count; i < m_iTotalAudioSourcesCount; ++i)
        {
            sm_aAudioSource.Add(new AudioHandlerManager(CreateAudioSource()));
        }
    }