Пример #1
0
        private ISoundVoice StartNewMoodSound(MoodSoundKey currentMood)
        {
            if (_currentlyPlayingMoodSound != null)
            {
                if (_currentlyPlayingMoodSound.IsPlaying)
                {
                    _currentlyPlayingMoodSound.Stop(5000);
                    _currentlyPlayingMoodSound = null;
                }
            }

            //MoodsSounds.Keys[1].
            List <IUtopiaSoundSource> soundSource;

            if (MoodsSounds.TryGetValue(currentMood, out soundSource))
            {
                IUtopiaSoundSource sound = soundSource[_rnd.Next(0, soundSource.Count)];
                _currentlyPlayingMoodSound = SoundEngine.StartPlay2D(sound.Alias, SourceCategory.Music, false, 5000);
                return(_currentlyPlayingMoodSound);
            }
            else
            {
                return(null);
            }
        }
Пример #2
0
 public void StartVoiceDataFetching(ISoundVoice voice)
 {
     if (_fetchingThread != null &&
         _fetchingThread.Status != TaskStatus.RanToCompletion &&
         _fetchingThread.Status != TaskStatus.Faulted &&
         _fetchingThread.Status != TaskStatus.Canceled &&
         _fetchingThread.Status != TaskStatus.Created
         )
     {
         //logger.Warn("Cannot stream the same resource as streaming source for 2 differents voices !! Previously playing sound will be stopped");
         lock (_syncRoot)
         {
             if (_linkedVoice != null)
             {
                 _linkedVoice.Stop();
             }
         }
         _sleep.Set();
         _fetchingThread.Wait();
     }
     _linkedVoice           = voice;
     _linkedVoice.IsPlaying = true;
     //Start voice Fetching with data !
     _fetchingThread = Task.Factory.StartNew(asyncVoiceFetching, TaskCreationOptions.LongRunning);
 }
Пример #3
0
 private void processLoopingSoundState(ISoundVoice soundVoice)
 {
     if (soundVoice.State.BuffersQueued == 0)
     {
         soundVoice.PushDataSourceForPlaying();
     }
 }
Пример #4
0
        private bool GetVoice(ISoundDataSource dataSource2Bplayed, out ISoundVoice soundVoice)
        {
            //Get the soundqueue following SoundFormatCategory
            ISoundVoice[] voiceQueue;
            if (!_soundVoices.TryGetValue(dataSource2Bplayed.GetSoundFormatCategory(), out voiceQueue))
            {
                _soundVoices.Add(dataSource2Bplayed.GetSoundFormatCategory(), voiceQueue = new ISoundVoice[_maxVoicePoolPerFileType]);
            }

            //Check for a voice IDLE in the voice pool for this type of sound file.
            long        oldestTimerTick  = -1;
            ISoundVoice oldestSoundVoice = null;

            for (int i = 0; i < _maxVoicePoolPerFileType; i++)
            {
                soundVoice = voiceQueue[i];
                if (soundVoice == null)
                {
                    //logger.Info("NEW Voice Id : {0}, for queue {1} song playing {2}", i, dataSource2Bplayed.WaveFormat.ToString(), dataSource2Bplayed.SoundAlias);
                    soundVoice         = voiceQueue[i] = ToDispose(new SoundVoice(this, dataSource2Bplayed.WaveFormat, Voice_BufferEnd));
                    soundVoice.Id      = i + "  dataSource2Bplayed.WaveFormat.ToString()";
                    soundVoice.Emitter = new Emitter()
                    {
                        ChannelCount        = 1,
                        CurveDistanceScaler = float.MinValue
                    };
                    return(true); //Return a newly created voice
                }
                if (soundVoice.IsPlaying == false)
                {
                    //logger.Info("Reuse Voice Id {0}, for queue {1} song playing {2}", i, dataSource2Bplayed.WaveFormat.ToString(), dataSource2Bplayed.SoundAlias);

                    return(true);  //Return an already created voice, that was waiting to play a sound
                }
                else
                {
                    //If a priority is given, then try to find the oldest sound with lower or equal priority
                    if (dataSource2Bplayed.Priority > 0 && soundVoice.Priority <= dataSource2Bplayed.Priority)
                    {
                        if (oldestTimerTick < soundVoice.PlayingTime.ElapsedTicks)
                        {
                            oldestSoundVoice = soundVoice;
                            oldestTimerTick  = soundVoice.PlayingTime.ElapsedTicks;
                        }
                    }
                }
            }

            if (oldestSoundVoice != null)
            {
                oldestSoundVoice.Stop();
                soundVoice = oldestSoundVoice;
                return(true);
            }
            else
            {
                soundVoice = null;
                return(false);
            }
        }
Пример #5
0
        public ISoundVoice StartPlay2D(ISoundDataSource soundSource, float volume, bool playLooped = false, uint fadeIn = 0, uint minDefferedStart = 0, uint maxDefferedStart = 0)
        {
            if (soundSource == null)
            {
                throw new ArgumentNullException();
            }

            ISoundVoice soundVoice = null;

            //Get an Idle voice ready to play a buffer
            if (GetVoice(soundSource, out soundVoice))
            {
                soundVoice.is3DSound         = false;
                soundVoice.IsLooping         = playLooped;
                soundVoice.PlayingDataSource = soundSource;
                if (maxDefferedStart == 0)
                {
                    soundVoice.PushDataSourceForPlaying();
                }
                soundVoice.RefreshVoices();
                soundVoice.MaxDefferedStart = maxDefferedStart;
                soundVoice.MinDefferedStart = minDefferedStart;
                soundVoice.Start(volume, fadeIn);
                if (playLooped || fadeIn > 0 || maxDefferedStart > 0)
                {
                    AddSoundWatching(soundVoice);
                }
            }
            else
            {
                logger.Warn("Sound playing skipped because no sound channel are IDLE : {0}", soundSource.Alias);
            }

            return(soundVoice);
        }
Пример #6
0
 public void AddSoundWatching(ISoundVoice voice)
 {
     lock (_soundQueueSync)
     {
         _soundProcessingQueue.Add(voice);
     }
     _syncro.Set();
 }
Пример #7
0
        private void AmbiantSoundProcessing(VisualChunk chunk, ICharacterEntity player)
        {
            ChunkColumnInfo columnInfo = chunk.BlockData.GetColumnInfo(player.Position.ToCubePosition().X - chunk.ChunkPositionBlockUnit.X, player.Position.ToCubePosition().Z - chunk.ChunkPositionBlockUnit.Y);

            bool playerAboveMaxChunkheight = (columnInfo.MaxHeight - player.Position.ToCubePosition().Y < -15);
            bool playerBelowMaxChunkheight = (columnInfo.MaxHeight - player.Position.ToCubePosition().Y > 15);

            Biome currentBiome = _biomesParams.Biomes[chunk.BlockData.ChunkMetaData.ChunkMasterBiomeType];

            //Ambiant sound are just for surface "chunk", if not stop playing them !
            if (playerAboveMaxChunkheight || playerBelowMaxChunkheight || player.HealthState == DynamicEntityHealthState.Dead)
            {
                if (_currentlyPLayingAmbiantSound != null)
                {
                    if (_currentlyPLayingAmbiantSound.IsPlaying)
                    {
                        _currentlyPLayingAmbiantSound.Stop(1000);
                        _currentlyPLayingAmbiantSound = null;
                    }
                    _previousBiomePlaying = null;
                }
                return;
            }

            //IF first pass or biome did change or currently player sound is finished
            if (
                _previousBiomePlaying == null ||
                currentBiome != _previousBiomePlaying ||
                (_currentlyPLayingAmbiantSound != null && _currentlyPLayingAmbiantSound.IsPlaying == false)
                )
            {
                if (_currentlyPLayingAmbiantSound != null)
                {
                    if (_currentlyPLayingAmbiantSound.IsPlaying)
                    {
                        _currentlyPLayingAmbiantSound.Stop(1000);
                        _currentlyPLayingAmbiantSound = null;
                    }
                }
                //Pickup next biome ambiant sound, and start it !
                if (currentBiome.AmbientSound.Count > 0)
                {
                    int nextAmbientSoundId = _rnd.Next(0, currentBiome.AmbientSound.Count);
                    _currentlyPLayingAmbiantSound = _soundEngine.StartPlay2D(currentBiome.AmbientSound[nextAmbientSoundId].Alias, SourceCategory.Music, false, 3000);
                    _previousBiomePlaying         = currentBiome;
                }
            }
        }
Пример #8
0
        public void Use()
        {
            Enabled = !Enabled;

            if (MusicTrack != null && SoundEngine != null)
            {
                if (Enabled)
                {
                    _voice = SoundEngine.StartPlay3D(MusicTrack, Position.AsVector3(), true);
                }
                else
                {
                    if (_voice != null)
                    {
                        _voice.Stop();
                        _voice = null;
                    }
                }
            }
        }
Пример #9
0
        public ISoundVoice StartPlay3D(ISoundDataSource soundSource, Vector3 position, float volume, bool playLooped = false, uint minDefferedStart = 0, uint maxDefferedStart = 0)
        {
            if (soundSource == null)
            {
                throw new ArgumentNullException();
            }

            ISoundVoice soundVoice = null;

            if (GetVoice(soundSource, out soundVoice))
            {
                soundVoice.Emitter.Position  = position;
                soundVoice.Emitter.OrientTop = Vector3.UnitY;
                soundVoice.Emitter.Velocity  = Vector3.Zero;

                soundVoice.is3DSound         = true;
                soundVoice.IsLooping         = playLooped;
                soundVoice.PlayingDataSource = soundSource;
                if (maxDefferedStart == 0)
                {
                    soundVoice.PushDataSourceForPlaying();
                }
                soundVoice.RefreshVoices();
                soundVoice.MaxDefferedStart = maxDefferedStart;
                soundVoice.MinDefferedStart = minDefferedStart;
                soundVoice.Start(volume);
                if (playLooped || maxDefferedStart > 0)
                {
                    AddSoundWatching(soundVoice);
                }
            }
            else
            {
                logger.Warn("Sound playing skipped because no sound channel are IDLE : {0}", soundSource.Alias);
            }

            return(soundVoice);
        }
Пример #10
0
        //Async
        private void asyncVoiceFetching()
        {
            int nextBuffer = 0;

            while (!_stopThread && _linkedVoice != null && _linkedVoice.IsPlaying)
            {
                // Get the decoded samples from the specified starting position.
                var sampleIterator = _audioDecoder.GetSamples().GetEnumerator();

                // Playing all the samples
                while (true)
                {
                    // If ring buffer queued is full, wait for the end of a buffer.
                    while (_linkedVoice.State.BuffersQueued == bufferRing && !_stopThread && _linkedVoice.IsPlaying)
                    {
                        _sleep.WaitOne(1);
                    }

                    // If the player is stopped or disposed, then break of this loop
                    if (_stopThread || !_linkedVoice.IsPlaying)
                    {
                        break;
                    }

                    // Check that there is a next sample
                    if (!sampleIterator.MoveNext())
                    {
                        break;
                    }

                    // Retrieve a pointer to the sample data
                    var bufferPointer = sampleIterator.Current;

                    // Check that our ring buffer has enough space to store the audio buffer.
                    if (bufferPointer.Size > _memBuffers[nextBuffer].Size)
                    {
                        if (_memBuffers[nextBuffer].Pointer != IntPtr.Zero)
                        {
                            Utilities.FreeMemory(_memBuffers[nextBuffer].Pointer);
                        }

                        _memBuffers[nextBuffer].Pointer = Utilities.AllocateMemory(bufferPointer.Size);
                        _memBuffers[nextBuffer].Size    = bufferPointer.Size;
                    }

                    // Copy the memory from MediaFoundation AudioDecoder to the buffer that is going to be played.
                    Utilities.CopyMemory(_memBuffers[nextBuffer].Pointer, bufferPointer.Pointer, bufferPointer.Size);

                    // Set the pointer to the data.
                    _audioBuffersRing[nextBuffer].AudioDataPointer = _memBuffers[nextBuffer].Pointer;
                    _audioBuffersRing[nextBuffer].AudioBytes       = bufferPointer.Size;

                    // Submit the audio buffer to xaudio2
                    _linkedVoice.Voice.SubmitSourceBuffer(_audioBuffersRing[nextBuffer], null);

                    // Go to next entry in the ringg audio buffer
                    nextBuffer = ++nextBuffer % bufferRing;
                }

                // If the song is not looping go out the while
                if (!_linkedVoice.IsLooping)
                {
                    break;
                }
            }

            lock (_syncRoot)
            {
                _linkedVoice.Stop();
                _linkedVoice = null;
            }
        }
Пример #11
0
        private void StaticEntitiesEmittedSoundProcessing()
        {
            IItem[] collectedStaticItems = new IItem[100];
            IItem[] nearestEntities      = new IItem[_qtPlayingSound];
            IItem[] entitiesSet          = new IItem[_qtPlayingSound];

            int i = 0;

            //Collection surrending "Sound" entities (Max of 100) ===========================================
            foreach (VisualChunk chunk in _worldChunk.SortedChunks.Where(x => x.DistanceFromPlayer < _collectRange))
            {
                foreach (var soundStaticEntities in chunk.SoundStaticEntities)
                {
                    collectedStaticItems[i] = soundStaticEntities;
                    i++;
                    if (i >= collectedStaticItems.Length)
                    {
                        break;
                    }
                }
                if (i >= collectedStaticItems.Length)
                {
                    break;
                }
            }
            for (; i < collectedStaticItems.Length; i++)
            {
                collectedStaticItems[i] = null;
            }

            // Sorting array by distance from Player
            i = 0;
            foreach (var entity in collectedStaticItems.Where(x => x != null).OrderBy(x => MVector3.DistanceSquared(x.Position, _playerEntityManager.CameraWorldPosition)))
            {
                nearestEntities[i] = entity;
                i++;
                if (i >= _qtPlayingSound)
                {
                    break;                       //Maximum playing 10 closest static sound at the same time
                }
            }
            for (; i < _qtPlayingSound; i++)
            {
                nearestEntities[i] = null;
            }

            //Get entities remove from playing list.
            i = 0;
            entitiesSet[0] = null;
            foreach (var entities in _staticEntityPlayingVoices.Keys.Except(nearestEntities))
            {
                entitiesSet[i] = entities;
                i++;
            }
            for (i--; i >= 0; i--)
            {
                if (entitiesSet[i] == null)
                {
                    break;
                }
                if (_staticEntityPlayingVoices[entitiesSet[i]] != null)
                {
                    _staticEntityPlayingVoices[entitiesSet[i]].Stop();
                }
                _staticEntityPlayingVoices.Remove(entitiesSet[i]);
            }

            ISoundVoice voice;

            foreach (var entities in nearestEntities.Where(x => x != null))
            {
                if (_staticEntityPlayingVoices.TryGetValue(entities, out voice) == false)
                {
                    ISoundVoice playingVoice = _soundEngine.StartPlay3D(entities.EmittedSound, entities.Position.AsVector3(), entities.EmittedSound.isLooping, entities.EmittedSound.minDeferredStart, entities.EmittedSound.maxDeferredStart);
                    _staticEntityPlayingVoices.Add(entities, playingVoice);
                }
                else
                {
                    if (voice == null)
                    {
                        ISoundVoice playingVoice = _soundEngine.StartPlay3D(entities.EmittedSound, entities.Position.AsVector3(), entities.EmittedSound.isLooping, entities.EmittedSound.minDeferredStart, entities.EmittedSound.maxDeferredStart);
                        _staticEntityPlayingVoices[entities] = playingVoice;
                    }
                }
            }
        }
Пример #12
0
 private void processFadingSoundState(ISoundVoice soundVoice)
 {
     soundVoice.RefreshVoices();
 }