Example #1
0
        /// <summary>
        /// Plays a <see cref="Sound"/> asynchronously.
        /// </summary>
        /// <param name="sound">A <see cref="Sound"/>.</param>
        /// <param name="loop">A value indicating whether playback should be looped.</param>
        /// <returns><c>true</c> if the <see cref="Sound"/> plays successfully, or <c>false</c> otherwise.</returns>
        public bool Play(Sound sound, bool loop)
        {
            this.ThrowIfDisposed();

            // Stop all playback
            if (!this.Stop())
            {
                return false;
            }

            // Do not play nothing
            if (sound == null)
            {
                return true;
            }

            try
            {
                this.IsPlaying = true;
                this.IsLooping = loop;

                if (sound.IsBuiltIn)
                {
                    // Use the sound player
                    this.soundPlayer.Stream = sound.GetStream();

                    if (loop)
                    {
                        // Asynchronously play looping sound
                        this.soundPlayer.PlayLooping();
                    }
                    else
                    {
                        // Asynchronously play sound once
                        this.soundPlayer.Play();

                        // Start a timer to notify the completion of playback if we know the duration
                        if (sound.Duration.HasValue)
                        {
                            this.dispatcherTimer.Interval = sound.Duration.Value;
                            this.dispatcherTimer.Start();
                        }
                    }
                }
                else
                {
                    // Use the media player
                    this.mediaPlayer.Open(new Uri(sound.Path));
                    this.mediaPlayer.Play();
                }
            }
            catch
            {
                return false;
            }

            // Raise an event
            this.OnPlaybackStarted();
            return true;
        }