/// <summary>
        /// Loads a sound track asset.
        /// </summary>
        /// <param name="path">Sound track path.</param>
        /// <param name="useCache">Should we use cache for this asset to make future loadings faster?</param>
        /// <param name="useAssetsRoot">If true, path will be relative to 'AssetsRoot'. If false, will be relative to working directory.</param>
        /// <returns>Loaded sound asset.</returns>
        public SoundAsset LoadSound(string path, bool useCache = true, bool useAssetsRoot = true)
        {
            var ret = new SoundAsset(_BonEngineBind.BON_Assets_LoadSound(ToAssetsPath(path, true, useAssetsRoot), useCache));

            ret.Path = path;
            return(ret);
        }
Example #2
0
    private IEnumerator WaitAndDelete(SoundAsset s)
    {
        GameObject sTemp = GameObject.Instantiate(s.aSource.gameObject, Vector3.zero, Quaternion.identity) as GameObject;

        yield return(new WaitForSeconds(s.aSource.clip.length + 1));

        Destroy(sTemp);
    }
Example #3
0
 /// <summary>
 /// Play a sound effect.
 /// </summary>
 /// <param name="sound">Sound to play.</param>
 /// <param name="volume">Sound volume.</param>
 /// <param name="loops">How many times to repeat this sound (-1 = endless, 0 = once, above 0 = number of times).</param>
 /// <param name="pitch">Sound pitch effect.</param>
 /// <param name="panLeft">Pan sound left - value should be 0.0-1.0.</param>
 /// <param name="panRight">Pan sound right - value should be 0.0-1.0.</param>
 /// <param name="distance">Sound source distance (affect volume) - value should be 0.0-1.0.</param>
 /// <param name="fadeInTime">Fade in time, in seconds (or 0 to play immediately).</param>
 /// <returns>Channel id, which you can use later to modify sound. Can be Invalid if there was no available channel.</returns>
 public SoundChannelId PlaySound(SoundAsset sound, int volume, int loops, float pitch, float panLeft, float panRight, float distance, float fadeInTime = 0f)
 {
     if (sound._handle == IntPtr.Zero)
     {
         throw new Exception("Can't play sound asset with null handle!");
     }
     return(_BonEngineBind.BON_Sfx_PlaySoundEx(sound._handle, volume, loops, pitch, panLeft, panRight, distance, fadeInTime));
 }
Example #4
0
 /// <summary>
 /// Play a sound effect.
 /// </summary>
 /// <param name="sound">Sound to play.</param>
 /// <param name="volume">Sound volume.</param>
 /// <param name="loops">How many times to repeat this sound (-1 = endless, 0 = once, above 0 = number of times).</param>
 /// <param name="pitch">Sound pitch effect.</param>
 /// <param name="fadeInTime">Fade in time, in seconds (or 0 to play immediately).</param>
 /// <returns>Channel id, which you can use later to modify sound. Can be Invalid if there was no available channel.</returns>
 public SoundChannelId PlaySound(SoundAsset sound, int volume = 100, int loops = 0, float pitch = 1f, float fadeInTime = 0f)
 {
     if (sound._handle == IntPtr.Zero)
     {
         throw new Exception("Can't play sound asset with null handle!");
     }
     return(_BonEngineBind.BON_Sfx_PlaySound(sound._handle, volume, loops, pitch, fadeInTime));
 }
    public static int PlaySound(SoundAsset asset, GameObject transformObject)
    {
        if (!VerifySingleton())
        {
            return(INVALID_SOUND);
        }

        return(SoundManagerComponent.instance.PlaySoundInternal(asset, transformObject));
    }
    public static int PlaySound(SoundAsset asset)
    {
        if (!VerifySingleton())
        {
            return(INVALID_SOUND);
        }

        return(SoundManagerComponent.instance.PlaySoundInternal(asset, null));
    }
Example #7
0
    public void SetVolume(string SoundName, float Volume)
    {
        SoundAsset S = Array.Find(Sounds, Sound => Sound.Name == SoundName);

        if (S == null)
        {
            Debug.LogError("Sound " + SoundName + " not found!");
        }
        S.Source.volume = Mathf.Lerp(S.Source.volume, Volume, Time.deltaTime);
    }
Example #8
0
    public void Play(string SoundName)
    {
        SoundAsset S = Array.Find(Sounds, Sound => Sound.Name == SoundName);

        if (S == null)
        {
            Debug.LogError("Sound " + SoundName + " not found!");
        }
        S.Source.Play();
    }
Example #9
0
    public void PlaySoundByName(string name)
    {
        SoundAsset s = Array.Find(SoundAssets, sound => sound.name == name);

        if (s == null)
        {
            return;
        }
        s.source.Play();
    }
Example #10
0
        // load the scene
        protected override void Load()
        {
            // load fonts
            _font    = Assets.LoadFont("gfx/OpenSans-Regular.ttf", 22, false);
            _fontBig = Assets.LoadFont("gfx/OpenSans-Regular.ttf", 42, false);

            // load font and music
            _music = Assets.LoadMusic("sfx/old city theme.ogg");
            _sound = Assets.LoadSound("sfx/phaserUp1.mp3");

            // start playing music
            Sfx.PlayMusic(_music);
        }
Example #11
0
        // load the scene
        protected override void Load()
        {
            // load fonts
            _font    = Assets.LoadFont("gfx/OpenSans-Regular.ttf", 22, false);
            _fontBig = Assets.LoadFont("gfx/OpenSans-Regular.ttf", 42, false);

            // load font and music
            _music    = Assets.LoadMusic("sfx/old city theme.ogg");
            _altMusic = Assets.LoadMusic("sfx/forest.ogg");
            _sound    = Assets.LoadSound("sfx/phaserUp1.mp3");

            // start playing music via the music fader
            _musicFader = new MusicFader(null, 100, _music, 100);
        }
Example #12
0
        /// <summary>
        /// Loops a sound.
        /// </summary>
        /// <param name="soundBase">The SoundAsset to play.</param>
        /// <param name="position">The optional position to play it at.</param>
        /// <param name="volume">The optional volume of the sound.</param>
        /// <param name="pan">The optional panning of the sound.</param>
        /// <param name="pitch">The optional pitch adjustment of the sound.</param>
        /// <returns>The new sound.</returns>
        public Sound LoopSound(SoundAsset soundBase, Vector2? position = null, float volume = 1, float pan = 0, float pitch = 0)
        {
            Sound newSound = soundBase.CreateInstance();
            newSound.Volume = volume;
            newSound.Pan = pan;
            newSound.Pitch = pitch;
            newSound.Position = position;
            newSound.Environment = this;
            updateSound(newSound, false);
            newSound.Loop();
            soundsPlaying.Add(newSound);

            return newSound;
        }
Example #13
0
    private IEnumerator PlayLoopRoutine(SoundAsset sound, int soundID)
    {
        var audioSource = loopingSounds[soundID];

        audioSource.clip = sound.GetClip();
        audioSource.outputAudioMixerGroup = sound.Group;
        audioSource.Play();

        while (audioSource.isPlaying)
        {
            yield return(null);
        }

        // If the loop has been stopped, we can retire the audio source and break
        if (!loopingSounds.ContainsKey(soundID))
        {
            ReturnAudioSourceToPool(audioSource);
            yield break;
        }
        StartCoroutine(PlayLoopRoutine(sound, soundID));
    }
Example #14
0
        /// <summary>
        /// Plays a sound.
        /// </summary>
        /// <param name="soundBase">The SoundAsset to play.</param>
        /// <param name="position">The optional position to play it at.</param>
        /// <param name="volume">The optional volume of the sound.</param>
        /// <param name="pan">The optional panning of the sound.</param>
        /// <param name="pitch">The optional pitch adjustment of the sound.</param>
        /// <param name="fireAndForget">Indicates if the SoundEnvironment should delete the sound once it's finished.</param>
        /// <returns>The new sound, or null if fireAndForget is true.</returns>
        public Sound PlaySound(SoundAsset soundBase, Vector2? position = null, float volume = 1, float pan = 0, float pitch = 0, bool fireAndForget = true)
        {
            if (fireAndForget && !Active)
                return null;

            Sound newSound = soundBase.CreateInstance();
            newSound.Volume = volume;
            newSound.Pan = pan;
            newSound.Pitch = pitch;
            newSound.ShoulDestroyOnComplete = fireAndForget;
            newSound.Position = position;
            newSound.Environment = this;
            updateSound(newSound, false);
            newSound.Play();
            soundsPlaying.Add(newSound);

            return (fireAndForget ? newSound : null);
        }
Example #15
0
 internal Sound(SoundAsset parent, SoundEffectInstance instance)
 {
     Source = parent;
     Instance = instance;
 }
Example #16
0
 public SoundRefInternal(SoundAsset sound)
 {
     _sound = sound;
 }
Example #17
0
    private List <Asset> LoadDirectory(string path)
    {
        List <Asset> loadedAssets = new List <Asset>();

        string[] files = Directory.GetFiles(path);
        for (int i = 0; i < files.Length; i++)
        {
            string extension = Path.GetExtension(files[i]);
            if (Path.GetFileName(files[i]) == "addon.info" || extension == ".meta")
            {
                continue;
            }

            Asset asset;
            switch (extension)
            {
            case ".fbx":
                asset = new ModelAsset()
                {
                    files  = new string[] { files[i] },
                    source = this
                };

                if (asset.Load())
                {
                    loadedAssets.Add(asset);
                }
                else
                {
                    Debug.LogWarning($"Failed to load ModelAsset (does it need to be done in main thread?), Path: {files[i]}");
                }
                break;

            case ".png":
            case ".jpg":
            case ".jpeg":
                asset = new ImageAsset
                {
                    files  = new string[] { files[i] },
                    source = this
                };

                if (asset.Load())
                {
                    loadedAssets.Add(asset);
                }
                else
                {
                    Debug.LogWarning($"Failed to load ImageAsset (does it need to be done in main thread?), Path: {files[i]}");
                }
                break;

            case ".mp3":
            case ".ogg":
            case ".wav":
                asset = new SoundAsset
                {
                    files  = new string[] { files[i] },
                    source = this
                };

                if (asset.Load())
                {
                    loadedAssets.Add(asset);
                }
                else
                {
                    Debug.LogWarning($"Failed to load SoundAsset, Path: {files[i]}");
                }
                break;

            case ".txt":
            case ".cs":
            case ".scss":
            case ".html":
                asset = new TextAsset
                {
                    files  = new string[] { files[i] },
                    source = this
                };

                if (asset.Load())
                {
                    loadedAssets.Add(asset);
                }
                else
                {
                    Debug.LogWarning($"Failed to load TextAsset, Path: {files[i]}");
                }
                break;

            default:
                Debug.LogWarning($"Got unknown extension: {extension}");
                break;
            }
        }

        string[] directories = Directory.GetDirectories(path);
        for (int i = 0; i < directories.Length; i++)
        {
            loadedAssets.AddRange(LoadDirectory(directories[i]));
        }

        return(loadedAssets);
    }
Example #18
0
 /// <summary>
 /// Play a sound effect.
 /// </summary>
 /// <param name="sound">Sound to play.</param>
 /// <param name="volume">Sound volume.</param>
 /// <param name="loops">How many times to repeat this sound (-1 = endless, 0 = once, above 0 = number of times).</param>
 /// <param name="pitch">Sound pitch effect.</param>
 /// <returns>Channel id, which you can use later to modify sound. Can be Invalid if there was no available channel.</returns>
 public SoundChannelId PlaySound(SoundAsset sound, int volume = 100, int loops = 0, float pitch = 1f)
 {
     return(_BonEngineBind.BON_Sfx_PlaySound(sound._handle, volume, loops, pitch));
 }
Example #19
0
        /// <summary>
        /// Loads a sound track asset.
        /// </summary>
        /// <param name="filename">Sound track path.</param>
        /// <param name="useCache">Should we use cache for this asset to make future loadings faster?</param>
        /// <returns>Loaded sound asset.</returns>
        public SoundAsset LoadSound(string filename, bool useCache = true)
        {
            var ret = new SoundAsset(_BonEngineBind.BON_Assets_LoadSound(ToAssetsPath(filename, true), useCache));

            return(ret);
        }
    //##############################################################################################
    // This is the primary function for how a sound is set up and played TODO TODO
    //
    // This function returns the sound id of the record, for reference later. For example, a loop
    // can be started and the id cached, then stopped at a later time, using that id.
    //##############################################################################################
    public int PlaySoundInternal(SoundAsset asset, GameObject transformObject)
    {
        if (asset == null || asset.clip == null || asset.volume <= 0.0f)
        {
            return(INVALID_SOUND);
        }

        int index = GetValidSoundIndex(asset.priority);

        if (index != INVALID_SOUND)
        {
            AudioSource        source        = usedSources[index];
            AudioReverbFilter  reverb        = source.GetComponent <AudioReverbFilter>();
            AudioLowPassFilter lowPassFilter = source.GetComponent <AudioLowPassFilter>();

            // Setup source
            source.Stop();
            source.clip = asset.clip;
            source.loop = (asset.count == SoundCount.Looping);

            // Randomize the pitch if needed
            if (asset.pitchBend > 0.0f)
            {
                source.pitch = 1.0f + (Random.value * asset.pitchBend) - (asset.pitchBend * 0.5f);
            }
            else
            {
                source.pitch = 1.0f;
            }

            // Apply volume
            source.volume = asset.volume * globalVolume;

            // Position immediately before next update
            source.gameObject.transform.position = transformObject == null ? Vector3.zero : transformObject.transform.position;

            // setup records
            SoundRecord record = records[index];
            record.volume   = asset.volume;
            record.features = asset.features;
            record.priority = asset.priority;
            record.soundId  = soundIdIndex;
            record.parent   = transformObject;

            record.reverb        = reverb;
            record.lowPassFilter = lowPassFilter;

            soundIdIndex++;

            // Set defaults for advanced features
            bool delayed = false;
            reverb.reverbPreset           = AudioReverbPreset.Off;
            lowPassFilter.cutoffFrequency = SoundConstants.LPF_CLEAR;
            source.spatialBlend           = SoundConstants.SPATIAL_BLEND_TWO_D;

            // Advanced features require three-dimensional spatialization and a valid transform
            if ((asset.features & SoundFeatures.ThreeDimensional) != 0)
            {
                if (transformObject != null)
                {
                    source.spatialBlend = SoundConstants.SPATIAL_BLEND_THREE_D;

                    if ((asset.features & SoundFeatures.SimulatedReverb) != 0)
                    {
                        float physicalVolumeNormalized = CalculatePhysicalVolumeNormalized(record.parent);
                        ApplyReverbFromPhysicalVolume(reverb, physicalVolumeNormalized);

                        record.timeUntilReverbUpdate    = REVERB_UPDATE_TIME;
                        record.previousVolumeNormalized = physicalVolumeNormalized;
                        record.physicalVolumeNormalized = physicalVolumeNormalized;
                    }

                    if ((asset.features & SoundFeatures.Occlusion) != 0)
                    {
                        // Mark previous occlusion as invalid to immediately apply
                        record.currentOcclusion  = Occluded(transformObject);
                        record.previousOcclusion = record.currentOcclusion;

                        record.timeUntilOcclusionUpdate = OCCLUSION_UPDATE_TIME;

                        ApplyOcclusion(lowPassFilter, record.currentOcclusion);
                    }

                    if ((asset.features & SoundFeatures.DistanceDelayed) != 0)
                    {
                        delayed = true;
                    }

                    if ((asset.features & SoundFeatures.EmitsSlapbacks) != 0)
                    {
                        // TODO Shoot ray away from listener, and create delayed slapback at that point?
                    }

                    if ((asset.features & SoundFeatures.Doppler) != 0)
                    {
                        source.dopplerLevel = SoundConstants.DOPPLER_ON;
                    }
                    else
                    {
                        source.dopplerLevel = SoundConstants.DOPPLER_OFF;
                    }
                }

                if (transformObject == null && asset.features != 0)
                {
                    Logger.Error("All Sound Assets with Sound Features require a transform object as an argument.");
                    record.features = 0;
                }
            }

            // play the sound unless delayed
            if (!delayed)
            {
                source.Play();
            }

            return(records[index].soundId);
        }
        else
        {
            Logger.Warning("Failed to play " + asset.clip + " with priority " + asset.priority);
            return(INVALID_SOUND);
        }
    }
Example #21
0
 /// <summary>
 /// Play a sound effect.
 /// </summary>
 /// <param name="sound">Sound to play.</param>
 /// <param name="volume">Sound volume.</param>
 /// <param name="loops">How many times to repeat this sound (-1 = endless, 0 = once, above 0 = number of times).</param>
 /// <param name="pitch">Sound pitch effect.</param>
 /// <param name="panLeft">Pan sound left - value should be 0.0-1.0.</param>
 /// <param name="panRight">Pan sound right - value should be 0.0-1.0.</param>
 /// <param name="distance">Sound source distance (affect volume) - value should be 0.0-1.0.</param>
 /// <returns>Channel id, which you can use later to modify sound. Can be Invalid if there was no available channel.</returns>
 public SoundChannelId PlaySound(SoundAsset sound, int volume, int loops, float pitch, float panLeft, float panRight, float distance)
 {
     return(_BonEngineBind.BON_Sfx_PlaySoundEx(sound._handle, volume, loops, pitch, panLeft, panRight, distance));
 }
Example #22
0
        /// <summary>
        /// Sets a SoundAsset at the given key.
        /// </summary>
        public void SetMusicAsset(string key, SoundAsset asset)
        {
            if (asset == null)
                throw new Exception("Cannot add null asset");

            assets[key] = asset;
            availableSounds[key] = null;
            LoadMusic();
        }
Example #23
0
 public static Action <MouseEvent> ToMouseEvent(this SoundAsset c)
 {
     return(delegate { c.play(); });
 }
Example #24
0
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            base.LoadContent();

            Music1 = new SoundAsset("Portal2-23-You_Saved_Science", true);
            Music2 = new SoundAsset("Portal2-14-Spaaaaace", true);

            Playlist = new MusicPlaylist();
            Playlist.SetMusicAsset("music1", Music1);
            Playlist.SetMusicAsset("music2", Music2);

            Sounds = new SoundEnvironment();

            Assets = AssetCollection.FromFile("assets", true);
            Particles = AssetCollection.FromFile("SharedAssets/sharedAssets", true);
        }