Beispiel #1
0
        public async Task AddMusicTrackAsync(MusicTrack musicTrack)
        {
            if (musicTrack?.MusicVersions == null)
            {
                throw new ArgumentNullException(nameof(musicTrack));
            }

            using (var dataBase = new NameThatTuneDatabase())
            {
                if (await dataBase.MusicTrack.AnyAsync(o => o.Id == musicTrack.Id))
                {
                    throw new Exception($"Track {musicTrack.NameArtist} - {musicTrack.NameTrack} already exists");
                }

                ;
                var musicVersions = musicTrack.MusicVersions.ToArray();
                musicTrack.MusicVersions = null;
                await dataBase.MusicTrack.AddAsync(musicTrack);

                await dataBase.SaveChangesAsync();

                await dataBase.MusicVersions.AddRangeAsync(musicVersions);

                await dataBase.SaveChangesAsync();

                Console.Out.WriteLine("DB: Track {0} added", musicTrack.NameArtist + "-" + musicTrack.NameTrack);
            }
        }
Beispiel #2
0
 public bool MusicTrackExist(MusicTrack musicTrack)
 {
     using (var dataBase = new NameThatTuneDatabase())
     {
         return(dataBase.MusicTrack.Any(mt => mt.Id == musicTrack.Id));
     }
 }
Beispiel #3
0
    private IEnumerator FadeMusicCoroutine(float fadeDuration)
    {
        float startTimestamp = Time.time;
        float lerpAMT        = 0.0f;

        while (lerpAMT < 1.0f)
        {
            lerpAMT = (Time.unscaledTime - startTimestamp) / lerpAMT;
            if (lerpAMT > 1.0f)
            {
                lerpAMT = 1.0f;
            }

            introAudioSource.volume = 1.0f - lerpAMT;
            loopAudioSource.volume  = 1.0f - lerpAMT;
            yield return(null);
        }
        introAudioSource.volume = 0.0f;
        loopAudioSource.volume  = 0.0f;
        introAudioSource.Stop();
        loopAudioSource.Stop();
        introAudioSource.clip = null;
        loopAudioSource.clip  = null;
        CurrentlyPlayingTrack = null;
        yield return(null);

        introAudioSource.volume = 1.0f;
        loopAudioSource.volume  = 1.0f;
    }
        public async Task <IActionResult> PutMusicTrack([FromRoute] int id, [FromBody] MusicTrack musicTrack)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != musicTrack.ID)
            {
                return(BadRequest());
            }

            _context.Entry(musicTrack).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!MusicTrackExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Beispiel #5
0
    /// <summary>
    /// Starts playing a music track
    /// </summary>
    /// <param name="musicTrack"></param>
    /// <param name="delayedPlayBack"></param>
    /// <param name="loopMusic"></param>
    public void StartPlayingMusicTrack(MusicTrack musicTrack, float delayedPlayBack = 0.0f, bool loopMusic = true)
    {
        if (musicTrack == null)
        {
            Debug.LogError("StartPlayingMusicTrack() called but no music track was passed!");
            return;
        }

        musicTrack.InitializeAudioTracks();
        if (delayedPlayBack < 0)
        {
            delayedPlayBack = 0;
        }

        StopAllCoroutines();
        introAudioSource.Stop();
        loopAudioSource.Stop();
        introAudioSource.volume = 1.0f;
        loopAudioSource.volume  = 1.0f;
        introAudioSource.clip   = musicTrack.IntroTrack;
        introAudioSource.PlayScheduled(AudioSettings.dspTime + delayedPlayBack + 0.1d);
        introAudioSource.loop = false;
        loopAudioSource.clip  = musicTrack.LoopTrack;
        loopAudioSource.PlayScheduled(AudioSettings.dspTime + delayedPlayBack + 0.1d + musicTrack.IntroTrackDuration);
        loopAudioSource.loop  = loopMusic;
        CurrentlyPlayingTrack = musicTrack;
        if (loopMusic == false)
        {
            StartCoroutine(CheckIfMusicIsLooping(delayedPlayBack + 0.1f));
        }
    }
Beispiel #6
0
 private void OnTrackPlay(MusicTrack track)
 {
     Invoke("Hide", 5f);
     this.visible   = true;
     this.interpret = track.interpret;
     this.title     = track.title;
 }
        public MusicTrack Update(MusicTrack updatedRestaurant)
        {
            var entity = db.Tracks.Attach(updatedRestaurant);

            entity.State = EntityState.Modified;
            return(updatedRestaurant);
        }
Beispiel #8
0
        public List <MusicTrack> LoadDesk(byte DeskN)
        {
            List <MusicTrack> DeskList = new List <MusicTrack>();

            DataTable DeskData = ReadTable(@"SELECT desk.id, desk.number, files.file, 
	case when desk.title='' then files.title else desk.title end title, files.cycle  
FROM files INNER JOIN desk ON (desk.file = files.id) 
WHERE desk.desk_n = " + DeskN.ToString() + @" 
ORDER BY desk.`order`");

            for (int i = 0; i < DeskData.Rows.Count; i++)
            {
                Stream MS = new MemoryStream();
                MS.Write((byte[])DeskData.Rows[i].ItemArray[2], 0,
                         ((byte[])DeskData.Rows[i].ItemArray[2]).Length);
                MS.Position = 0;

                MusicTrack MT = new MusicTrack(MS,
                                               DeskData.Rows[i].ItemArray[1].ToString(), DeskData.Rows[i].ItemArray[3].ToString(),
                                               DeskData.Rows[i].ItemArray[4].ToString() == "1");
                DeskList.Add(MT);
            }

            return(DeskList);
        }
    public void ChangeTrack(MusicTrack track, TrackVariant trackVariant = TrackVariant.overlap)
    {
        if (musicSource.isPlaying)
        {
            int startTime = musicSource.timeSamples;
            currTrack = track;
            AudioClip clip = null;
            switch (trackVariant)
            {
            case TrackVariant.cut:
                clip = track.cut;
                break;

            case TrackVariant.overlap:
                clip = track.overlap;
                break;

            case TrackVariant.tail:
                clip = track.tail;
                break;
            }
            musicSource.clip        = clip;
            musicSource.timeSamples = startTime;
            ignore = true;
        }
        else
        {
            Debug.Log("Could not change music track because source was not playing.");
        }
    }
Beispiel #10
0
    public IEnumerator ManageMusic()
    {
        while (true)
        {
            yield return(new WaitUntil(() => source.isPlaying == false));

            if (nextTrack != null)
            {
                source.clip = nextTrack.cut;
                looped      = false;
                currTrack   = nextTrack;
                nextTrack   = null;
            }
            else
            {
                if (looped == false)
                {
                    source.clip = currTrack.cut;
                }
                else
                {
                    source.clip = currTrack.overlap;
                }
                looped = true;
            }

            source.Play();
        }
    }
Beispiel #11
0
    public void PlayQueueThread()
    {
        Debug.Log("[PlayQueueThread launched]");
        bassThreadRunning = true;
        if (usingLocalAudio == false)
        {
            PlayStream(audioStreams[bassStreamQueue].url);
        }
        else
        {
            int newPlayIndex = rand.Next(0, safeZoneTracks.Count);
            for (int i = 0; i < 100; i++)
            {
                if (newPlayIndex == lastPlayedIndex)
                {
                    newPlayIndex = rand.Next(0, safeZoneTracks.Count);
                }
            }

            currentTrack = safeZoneTracks[rand.Next(0, safeZoneTracks.Count)];
            string trackStr = cachedStreamingPath + "/" + safeZoneTracksRoot + "/" + currentTrack.filePath;
            PlayFile(trackStr);
            lastPlayedIndex = newPlayIndex;
            Debug.Log("[PlayQueueThread]: safe zone track (" + trackStr + ") started");

            triggerSongIndicator = true;
        }
        bassThreadRunning = false;
    }
Beispiel #12
0
        public override void OnMusicRequest(MusicTrack track)
        {
            TrackPlayer p = SpawnNewPlayer();

            p.PlayLooped(track);
            ExitTo(new SingleTrackPlayingState(p));
        }
Beispiel #13
0
        static MediaFactory CreateDiskFactory(bool changable = false)
        {
            MusicTrack[] tracks = new MusicTrack[]
            {
                new MusicTrack("Music Track 1", "Noone", new byte[1]),
                new MusicTrack("Music Track 2", "Someone", new byte[1]),
                new MusicTrack("Music Track 3", "Noone", new byte[1])
            };

            Photo[] photoes = new Photo[]
            {
                new Photo("Photo 1", "Some author", new System.Drawing.Bitmap(1, 1)),
                new Photo("Photo 2", "No author", new System.Drawing.Bitmap(1, 1)),
                new PhotoReference("Photo 3", "Some author", new Uri("file:///nothing.bmp"))
            };

            MediaFactory factory;

            if (changable)
            {
                factory = new SelectionFactory(tracks, photoes);
            }
            else
            {
                factory = new DiskFactory(tracks, photoes);
            }
            return(factory);
        }
 public static void Play(MusicTrack track)
 {
     if (!instance.isBusy && instance.musicSource.clip != instance.musicTracks[(int)track])
     {
         instance.StartCoroutine(instance.PlayRoutine(track));
     }
 }
Beispiel #15
0
    void MusicCue(MusicTrack track, bool enable, float dur, float time)
    {
        Fade trackFade = Instantiate(fade).GetComponent <Fade>();

        trackFade.OnBeginMethod = () => {
            if (enable)
            {
                track.Play(time);
            }
        };
        trackFade.OnLoopMethod = () => {
            float v = Mathf.Lerp(0, 1f, trackFade.time);
            track.SetVol(v);

            /*if(!enable){
             *      Color c2 = mancha1.color;
             *      //mancha1.color = new Color(c2.r,c2.g,c2.b,v);
             * }*/
        };
        trackFade.OnEndMethod = () => {
            if (!enable)
            {
                track.Stop();
            }
            trackFade.Destroy();
        };
        if (enable)
        {
            trackFade.StartFadeIn(dur);
        }
        else
        {
            trackFade.StartFadeOut(dur);
        }
    }
Beispiel #16
0
    public static void PlayTrack(MusicTrack track, bool loop)
    {
        AudioClip trackToPlay = null;

        switch (track)
        {
        case MusicTrack.Title: trackToPlay = instance.titleTrack; break;

        case MusicTrack.Intro: trackToPlay = instance.introTrack; break;

        case MusicTrack.Build: trackToPlay = instance.buildTrack; break;

        case MusicTrack.Defend: trackToPlay = instance.defendTrack; break;

        case MusicTrack.Win: trackToPlay = instance.winTrack; break;

        case MusicTrack.Lose: trackToPlay = instance.loseTrack; break;
        }
        if (trackToPlay != null)
        {
            instance.audioSource.Stop();
            instance.audioSource.loop = loop;
            instance.audioSource.clip = trackToPlay;
            instance.audioSource.Play();
        }
    }
Beispiel #17
0
    /*
     * This method plays a music track based on the enum MusicTrack parameter value. The values are as follows:
     * The used enum values: WorldMap = 0, BubbleWarehouse = 1, BubbleWarehouseCutscene = 2, EndingCutscene = 3, GameOverJingle = 4, HedgeMaze = 5,
     * HedgeMazeCutscene = 6, MysticCards = 7, MysticCardsCutscene = 8, VictoryJingle = 9, WinterForestMarathon = 10,
     * WinterForestMarathonCutscene = 11
     */
    private void Play(MusicTrack musicTrack)
    {
        AudioSource currentlyPlayingTrack = GetCurrentlyPlayingMusicTrack();

        int trackIndex = (int)musicTrack;

        //The track is a jingle that pauses the current track and resumes it after the jingle has played.
        if (trackIndex == 4 || trackIndex == 9)
        {
            StartCoroutine(PlayJingle(audioSources[trackIndex]));
            return;
        }

        //Ignore this function if the track is already playing.
        if (currentlyPlayingTrack.Equals(audioSources[(int)musicTrack]) && audioSources[(int)musicTrack].isPlaying)
        {
            return;
        }

        Stop();

        //If the track is the World map theme, it's starting time is loaded from the worldMapMusicSamples variable
        //which is updated in the Stop() -method.
        if (trackIndex == 0)
        {
            audioSources[0].timeSamples = worldMapMusicTimeSamples;
        }

        audioSources[trackIndex].Play();
        Debug.Log("New music track playing.");
    }
Beispiel #18
0
    public void ChangeMusic(MusicTrack track)
    {
        if (track == currentTrack)
        {
            return;
        }
        if (musicTrack != null)
        {
            musicTrack.source.Stop();
        }

        currentTrack = track;

        switch (track)
        {
        case MusicTrack.Saferoom:
            musicTrack = SaferoomSong;
            SaferoomSong.source.Play();
            break;

        case MusicTrack.Ambience:
            musicTrack = Ambience;
            Ambience.source.Play();
            break;

        case MusicTrack.Chase:
            musicTrack = Chase;
            Chase.source.Play();
            break;

        default:
            break;
        }
    }
    IEnumerator FadeInTrack(MusicTrack track, bool unloadOtherTracks, float fadeTime)
    {
        inFade      = true;
        fadeToTrack = track;
        AudioSource oldSource = currentSource;

        AudioSource fadeToSource = GetSource(track);

        fadeToSource.transform.parent      = transform;
        fadeToSource.outputAudioMixerGroup = mixerGroup;

        fadeToSource.volume = 0f;
        if (fadeToSource.isPlaying)
        {
            fadeToSource.UnPause();
        }
        else
        {
            fadeToSource.Play();
        }

        float dT = Time.deltaTime / fadeTime;
        float t  = 0;

        while (t < 1f)
        {
            fadeToSource.volume = t;
            if (oldSource != null)
            {
                oldSource.volume = 1f - t;
            }
            t += dT;
            yield return(null);
        }
        fadeToSource.volume = 1f;

        if (oldSource != null)
        {
            oldSource.volume = 0f;
            oldSource.Pause();
        }

        currentSource = fadeToSource;
        currentTrack  = fadeToTrack;

        if (unloadOtherTracks)
        {
            foreach (MusicTrack unload in loadedTracks.Keys)
            {
                if (unload != currentTrack)
                {
                    GameObject.Destroy(loadedTracks [unload].gameObject);
                }
            }
            loadedTracks.Clear();
            loadedTracks [currentTrack] = currentSource;
        }

        inFade = false;
    }
        /// <summary>
        /// Gets the music links asynchronously.
        /// </summary>
        /// <param name="phrase">The phrase.</param>
        /// <param name="words">The key words.</param>
        /// <returns>
        /// Music track data.
        /// </returns>
        /// <exception cref="MusicException">
        /// If nothing was found
        /// </exception>
        public async Task <MusicTrack> GetMusicLinksAsync(string phrase, string words)
        {
            MusicTrack result = null;

            while (phrase?.Length > 0 && (result?.Data == null || result.Data.Count == 0))
            {
                result = await GetTracksAsync(phrase);

                phrase = phrase.Substring(0, Math.Max(0, phrase.LastIndexOf(Delimeter)));
            }

            if (result?.Data != null && result.Data.Count > 0)
            {
                return(result);
            }

            if (words?.Length > 0)
            {
                foreach (var word in words.Split(Delimeter))
                {
                    result = await GetTracksAsync(word);

                    if (result?.Data != null && result.Data.Count > 0)
                    {
                        return(result);
                    }
                }
            }

            throw new MusicException(MusicErrorCode.NothingFound);
        }
 /// <summary>
 /// Method called to transition into another music track
 /// </summary>
 /// <param name="track">The music track to play</param>
 /// <param name="transitionDuration">The transition duration (fades out the current song and plays the next track / Set this to 0.0f if the song should be played instantly)</param>
 /// <param name="loopTrack">Whether or not the music track should loop</param>
 public void TransitionIntoMusicTrack(MusicTrack track, float transitionDuration = 0.0f, bool loopTrack = true)
 {
     // If the currently active track is null, then assign playerA to the active track
     if (currentlyActiveTrack == null)
     {
         currentlyActiveTrack = PlayerA;
     }
     // If the transition duration is less than 0, reset it to 0
     if (transitionDuration < 0)
     {
         transitionDuration = 0;
     }
     // If the currently active track player is not playing anything, then
     // just have it play this track assigned
     if (currentlyActiveTrack.CurrentlyPlayingTrack == null)
     {
         currentlyActiveTrack.StartPlayingMusicTrack(track, transitionDuration, loopTrack);
     }
     //Otherwise, stop playing the current track, fade out the track with the transition duration
     // Schedule the
     else
     {
         currentlyActiveTrack.StopPlayingMusicTrack(fadeDuration: transitionDuration);
         currentlyActiveTrack = currentlyActiveTrack == PlayerA ? PlayerB : PlayerA;
         currentlyActiveTrack.StartPlayingMusicTrack(track, delayedPlayBack: transitionDuration, loopMusic: loopTrack);
     }
 }
Beispiel #22
0
        public void PlayTrack(MusicTrack track, bool crossFade = true)
        {
            if (currentTrack == track)
            {
                return;
            }
            currentTrack = track;

            AudioClip clip = null;

            if (track == MusicTrack.MENU_THEME)
            {
                clip = menuTheme;
            }
            else if (track == MusicTrack.BOSS_THEME_SLOW)
            {
                clip = bossThemeSlow;
            }
            else if (track == MusicTrack.BOSS_THEME_FAST)
            {
                clip = bossThemeFast;
            }
            else if (track == MusicTrack.END_THEME)
            {
                clip = endTheme;
            }

            if (clip != null)
            {
                AudioManager.Instance.PlayMusic(clip,
                                                crossFade ? crossFadeDuration : 0);
            }
        }
        public GameObject CreateTrack()
        {
            GameObject gameObject = Resource.LoadPrefabInstance("Group", true);

            gameObject.GetComponent <CustomName>().customName_ = "Music Track";

            var component = gameObject.AddComponent <ZEventListener>();

            var track = new MusicTrack()
            {
                Name = "Unknown"
            };

            track.NewVersion();

            track.WriteObject(component);

            gameObject.ForEachILevelEditorListener(delegate(ILevelEditorListener listener)
            {
                listener.LevelEditorStart(true);
            });

            MonoBehaviour[] components = gameObject.GetComponents <MonoBehaviour>();

            foreach (MonoBehaviour monoBehaviour in components)
            {
                monoBehaviour.enabled = false;
            }

            LevelEditor editor = G.Sys.LevelEditor_;

            editor.AddGameObjectSilent(ref objectHandle, gameObject, null);

            return(gameObject);
        }
        public ActionResult Create([Bind(Include = "ID,AlbumID,Name,Genre,Format,Description,Length,Price,TrackImgUrl,TrackFileUrl")] MusicTrack musicTrack, HttpPostedFileBase trackFile, HttpPostedFileBase TrackImg)
        {
            if (ModelState.IsValid)
            {
                var albumToAddTo = db.Albums.Find(Convert.ToInt32(musicTrack.AlbumID));

                if (trackFile.ContentLength > 0)
                {
                    byte[] audio = new byte[trackFile.ContentLength];
                    trackFile.InputStream.Read(audio, 0, audio.Length);
                    musicTrack.TrackFile = audio;
                }
                if (TrackImg.ContentLength > 0)
                {
                    byte[] image = new byte[TrackImg.ContentLength];
                    TrackImg.InputStream.Read(image, 0, image.Length);
                    musicTrack.TrackImg = image;
                }

                if (albumToAddTo != null)
                {
                    albumToAddTo.Tracks.Add(musicTrack);
                }

                db.MusicTracks.Add(musicTrack);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(musicTrack));
        }
    IEnumerator TransitionTrack(MusicTrack from, MusicTrack to, Coroutine stopCoroutine)
    {
        if (from != null)
        {
            while (audioSource.volume > 0)
            {
                audioSource.volume -= (1f / from.fadeOut) * Time.deltaTime;
                yield return(null);
            }
            audioSource.Stop();
        }
        if (stopCoroutine != null)
        {
            StopCoroutine(stopCoroutine);
        }

        audioSource.volume = volume;
        if (to != null)
        {
            audioSource.PlayOneShot(to.intro);
            yield return(new WaitForSecondsRealtime(to.introTime));

            while (true)
            {
                audioSource.PlayOneShot(to.body);
                yield return(new WaitForSecondsRealtime(to.bodyTime));
            }
        }
    }
Beispiel #26
0
        public void DeleteMusicTrackMoodTags(MusicTrack musicTrack)
        {
            var tagsToDelete = context.MusicTrackMoodTags.Where(m => m.MusicTrackID == musicTrack.ID);

            context.MusicTrackMoodTags.RemoveRange(tagsToDelete);
            context.SaveChanges();
        }
Beispiel #27
0
            public CurrentMusicTrack(MusicTrack musicTrack, ProtoPlaylist playlist)
            {
                this.Playlist   = playlist;
                this.MusicTrack = musicTrack;
                // ensure the track is changed
                ComponentMusicSource.MusicResource = MusicResource.NoMusic;
                ComponentMusicSource.MusicResource = musicTrack.MusicResource;
                ComponentMusicSource.IsLooped      = musicTrack.IsLooped;
                this.CurrentFadeInDuration         = musicTrack.FadeInDuration;
                this.CurrentFadeOutDuration        = musicTrack.FadeOutDuration;

                if (MusicTrackLastStopTimeManager.TryGetLastStopTime(musicTrack.MusicResource, out var lastStopTime))
                {
                    this.startAtPosition = lastStopTime;
                    ComponentMusicSource.Seek(lastStopTime);
                    Logger.Important($"Resume music {musicTrack.MusicResource} from {lastStopTime}");
                }
                else
                {
                    this.startAtPosition = null;
                }

                this.Update();
                ComponentMusicSource.Play();
            }
Beispiel #28
0
        static void Main(string[] args)
        {
            MusicTrack m = new MusicTrack(artist: "Rob Miles", title: "My Way", length: 150);

            Console.WriteLine(m);
            Console.ReadKey();
        }
Beispiel #29
0
        public async Task <IActionResult> Edit(int id, [Bind("ID,Artist,Title,Length")] MusicTrack musicTrack)
        {
            if (id != musicTrack.ID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(musicTrack);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!MusicTrackExists(musicTrack.ID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(musicTrack));
        }
Beispiel #30
0
        public MusicTrack[] ParseResponseToTracks(string response)
        {
            if (response == null)
            {
                throw new ArgumentNullException(nameof(response));
            }

            var musicTracks = new List <MusicTrack>();
            var block       = JObject.Parse(response);
            var results     = block["results"].Where(x => x["kind"].ToString() == "song").ToArray();

            if (results.Length == 0)
            {
                return(new MusicTrack[0]);
            }
            foreach (var token in results)
            {
                var trackUrl = token["previewUrl"].ToString();
                if (!IsValidUrl(trackUrl))
                {
                    Console.Out.WriteLine("trackUrl is invalid = {0}", trackUrl);
                    continue;
                }
                var track = new MusicTrack()
                {
                    NameArtist = token["artistName"].ToString(),
                    NameTrack  = token["trackName"].ToString(),
                    Id         = int.Parse(token["trackId"].ToString()),
                    UriTrack   = trackUrl
                };
                musicTracks.Add(track);
            }

            return(musicTracks.ToArray());
        }
Beispiel #31
0
        public void Test_New()
        {
            var track = new MusicTrack ("nice_music.ogg");

            Assert.AreEqual ("nice_music.ogg", track.FileName);
            Assert.AreEqual (1.0f, track.Volume);
            Assert.AreEqual (92891, track.Duration);
        }
Beispiel #32
0
        public void Test_Play_and_Stop()
        {
            var track = new MusicTrack ("nice_music.ogg");

            track.Play ();
            Assert.AreEqual (true, track.IsPlaying);

            track.Stop ();
            Assert.AreEqual (false, track.IsPlaying);
        }
Beispiel #33
0
        public void Test_SetVolume()
        {
            var track = new MusicTrack ("nice_music.ogg");

            track.Volume = 0.1f;
            Assert.AreEqual (0.1f, track.Volume, 0.1f);

            track.Volume = 0.2f;
            Assert.AreEqual (0.2f, track.Volume, 0.1f);
        }
Beispiel #34
0
        public static void Play(MusicTrack track)
        {
            Track = track;

            Instance = GetEffectByTrack(track).CreateInstance();
            Instance.Play();

            Instance.Volume = Volume;
            Instance.Pitch = Pitch;
            Instance.Pan = Pan;
        }
        /// <summary>
        /// Starts streaming music from a designated file.
        /// </summary>
        /// <param name="Path">The path to the file.</param>
        /// <param name="ID">The ID of the file.</param>
        /// <param name="Loop">Whether or not to loop the playback.</param>
        /// <returns>The music track's channel.</returns>
        public int LoadMusicTrack(string Path, int ID, bool Loop)
        {
            int Channel = Bass.BASS_StreamCreateFile(Path, 0, 0, BASSFlag.BASS_DEFAULT);

            if (Loop)
                Bass.BASS_ChannelFlags(Channel, BASSFlag.BASS_MUSIC_LOOP, BASSFlag.BASS_MUSIC_LOOP);

            MusicTrack Track = new MusicTrack(ID, Channel);
            m_Tracks.Add(Track);

            Bass.BASS_ChannelPlay(Channel, false);

            return Channel;
        }
Beispiel #36
0
    public MusicTrack GetNextTrack(MusicTrack previousTrack)
    {
        int numOfTracksLeft;
        MusicTrack newTrack = null;
        int index = -1;

        // Get next track
        if(tracksLeftToPlay == null) {
            tracksLeftToPlay = new List<MusicTrack>(tracks);
            numOfTracksLeft = tracksLeftToPlay.Count;

            for(int i = 0; i < tracksLeftToPlay.Count; i++) {
                if(tracksLeftToPlay[i].isFirstTrack) {
                    index = i;
                    break;
                }
            }
        } else {
            numOfTracksLeft = tracksLeftToPlay.Count;
        }

        if(index == -1) {
            while(true) {
                index = Random.Range(0, numOfTracksLeft);

                // Don't select the same audio clip again
                if(previousTrack == null || numOfTracksLeft == 1 || tracksLeftToPlay[index].audioClip != previousTrack.audioClip)
                    break;
            }
        }

        newTrack = tracksLeftToPlay[index];
        newTrack.playCount += 1;

        // Remove picked track from the "left to play" list
        if(tracksLeftToPlay.Count > 1) {
            tracksLeftToPlay.RemoveAt(index);
        } else {
            // Refill playlist
            tracksLeftToPlay = new List<MusicTrack>(tracks);
        }

        return newTrack;
    }
Beispiel #37
0
        /// <summary>
        ///     Constructs the music data object.
        /// </summary>
        /// <returns></returns>
        /// <summary>
        ///     Organizes the tracks In a Logical View.
        /// </summary>
        /// <returns></returns>
        public List<MusicData> OrganizeTracks()
        {
            var listMusicData = new List<MusicData>();
            var rating = new Rating();
            var listOfSongsDs = Db.get_music();

            foreach (DataRow r in listOfSongsDs.Tables[0].Rows)
            {
                var musicData = new MusicTrack
                {
                    MusicId = Convert.ToInt32(r["MusicID"]),
                    UserId = Convert.ToInt32(r["UserID"]),
                    SongName = r["Title"].ToString(),
                    PictureLocation = r["Picture"].ToString(),
                    LinkLocation = r["Link"].ToString(),
                    CanDownload = Convert.ToBoolean(r["CanDownload"]),
                    DateAdded = Convert.ToDateTime(r["DateAdded"]),
                    Rating = 0,
                    TotalVotes = 0,
                };

                if (!r.IsNull("RatingValue"))
                {
                    rating.Value = Convert.ToInt32(r["RatingValue"]);
                }

                var found = listMusicData.Any(x => x.MusicTrackData.MusicId == musicData.MusicId);

                if (found) //if else statement to remove rating of 0 that is added in db
                {
                    listMusicData.Find(x => x.MusicTrackData.MusicId == musicData.MusicId).RatingValues.Add(rating);
                }
                else
                {
                    listMusicData.Add(new MusicData {MusicTrackData = musicData});
                }
            }


            return listMusicData;
        }
Beispiel #38
0
        /// <summary>
        ///     Gets all the Top Tracks, No Limits
        /// </summary>
        /// <returns></returns>
        public List<MusicTrack> GetTopTracks()
        {
            var musicTracks = new List<MusicTrack>();
            var ranking = 1;
            var musicList = OrganizeTracks();
            foreach (var ml in musicList.Where(ml => ml.RatingValues.Count != 0))
            {
                ml.MusicTrackData.TotalVotes = ml.RatingValues.Count;
                ml.MusicTrackData.Rating = ml.RatingValues.Average(x => x.Value);
            }

            musicList =
                musicList.OrderByDescending(x => x.MusicTrackData.Rating)
                    .ThenByDescending(x => x.MusicTrackData.TotalVotes)
                    .ToList();

            foreach (var ml in musicList)
            {
                var mt = new MusicTrack();

                // ReSharper disable once CompareOfFloatsByEqualityOperator
                if (ml.MusicTrackData.Rating != 0)
                {
                    mt.MusicId = ml.MusicTrackData.MusicId;
                    mt.UserId = ml.MusicTrackData.UserId;
                    mt.TotalVotes = ml.MusicTrackData.TotalVotes;
                    mt.SongName = ml.MusicTrackData.SongName;
                    mt.Rating = ml.MusicTrackData.Rating;
                    mt.LinkLocation = ml.MusicTrackData.LinkLocation;
                    mt.PictureLocation = ml.MusicTrackData.PictureLocation;
                    mt.DateAdded = ml.MusicTrackData.DateAdded;
                    mt.CanDownload = ml.MusicTrackData.CanDownload;
                    mt.Ranking = ranking;
                    musicTracks.Add(mt);
                    ranking++;
                }
            }

            return musicTracks;
        }
Beispiel #39
0
 public void PlayMusic(MusicTrack sound, float delay = 0)
 {
     StopMusic();
     ClearPlaylist();
     Debug.Log("Playing: " + sound);
     AudioSources[MUSIC].clip = MusicTracks[(int)sound];
     AudioSources[MUSIC].PlayDelayed(delay);
 }
Beispiel #40
0
	// Plays the given music track, turning off all other music tracks.
	public void PlayMusic(MusicTrack musicTrack) {

		// Stop all currently playing music.
		music_menuTheme.Stop();
		music_mainTheme.Stop();
		music_victory.Stop();
		music_failure.Stop();

		// Play the requested track.
		switch (musicTrack) {
			case MusicTrack.MenuTheme: music_menuTheme.Play(); break;
			case MusicTrack.MainTheme: music_mainTheme.Play(); break;
			case MusicTrack.Victory: music_victory.Play(); break;
			case MusicTrack.Failure: music_failure.Play(); break;
			default: break;
		}
	}
Beispiel #41
0
    public void PlayMusic(MusicTrack[] tracks, bool shuffle = false)
    {
        StopMusic();
        ClearPlaylist();
        playlist = tracks;
        this.shuffle = shuffle;

        playNext(true);
    }
Beispiel #42
0
        private static SoundEffect GetEffectByTrack(MusicTrack track)
        {
            if (track == MusicTrack.MenuThemeSong)
                return menuThemeSong;

            return null;
        }