Esempio n. 1
0
        public static void SkipPlayback(SpotifyWebAPI api)
        {
            //Console.WriteLine(Prog.Mot[6]);

            if (Convert.ToDouble(Prog.Mot[6]) < 7900)
            {
                api.SkipPlaybackToNext();
                PlaybackContext Music = api.GetPlayback();

                Console.WriteLine($"You are listening {Music.Item.Name} now!");
            }

            else if (Convert.ToDouble(Prog.Mot[6]) > 8750)
            {
                api.SkipPlaybackToPrevious();

                PlaybackContext Music2 = api.GetPlayback();
                Console.WriteLine($"You are listening {Music2.Item.Name} now!");
            }


            else
            {
            }
            Thread.Sleep(1000);
        }
Esempio n. 2
0
 private void GlobalHookMouseWheelExt(object sender, MouseEventExtArgs e)
 {
     if (e.IsHorizontalScroll)
     {
         timer.Stop();
         SpotifySeekerOverlaySetOpacity(0.75D);
         if (playbackContext == null)
         {
             playbackContext = spotifyWebAPI.GetPlayback();
             String currentTrackArtists = null;
             foreach (SimpleArtist simpleArtist in playbackContext.Item.Artists)
             {
                 currentTrackArtists += simpleArtist.Name + ", ";
             }
             currentTrackArtists = currentTrackArtists.TrimEnd(", ".ToCharArray());
             String currentTrackName = playbackContext.Item.Name;
             CurrentTrackLabelSetText(currentTrackArtists + " - " + currentTrackName);
             CurrentProgressLabelSetText(TimeSpan.FromMilliseconds(playbackContext.ProgressMs).ToString("mm\\:ss"));
         }
         if (e.Delta > 0)
         {
             seekBalance++;
         }
         else if (e.Delta < 0)
         {
             seekBalance--;
         }
         ProgressModifierLabelSetText(TimeSpan.FromMilliseconds((seekBalance * SeekIncrement)).ToString());
         FutureProgressLabelSetText(TimeSpan.FromMilliseconds(playbackContext.ProgressMs + (seekBalance * SeekIncrement)).ToString("mm\\:ss"));
         timer.Start();
     }
 }
Esempio n. 3
0
        public TrackInfo WhatIsNowPlaying()
        {
            DateTime expireDate = accessToken.CreateDate.AddSeconds(accessToken.ExpiresIn);

            if (DateTime.Compare(DateTime.Now, expireDate.AddMinutes(-1)) > 0)
            {
                accessToken        = authorization.RefreshToken(refreshToken.RefreshToken).Result;
                webApi.AccessToken = accessToken.AccessToken;
                if (accessToken.RefreshToken != null)
                {
                    refreshToken = accessToken;
                }
            }

            try
            {
                PlaybackContext context = webApi.GetPlayingTrack();
                if (context.IsPlaying && !TrackType.Ad.Equals(context.CurrentlyPlayingType))
                {
                    FullTrack track = context.Item;
                    return(new TrackInfo(track.Artists[0].Name, track.Name, track.Album.Images[0].Url));
                }
            }
            catch (AggregateException)
            { }
            return(null);
        }
Esempio n. 4
0
        public void GetTrackname(string command, string args)
        {
            var             chat    = this.pluginInterface.Framework.Gui.Chat;
            PlaybackContext context = _spotify.GetPlayingTrack();

            if (context.Item != null)
            {
                String songname = context.Item.Name;
                String artists  = "";
                for (int i = 0; i < context.Item.Artists.Count; i++)
                {
                    if (i == context.Item.Artists.Count - 1)
                    {
                        artists += context.Item.Artists[i].Name;
                    }
                    else
                    {
                        artists += context.Item.Artists[i].Name + " - ";
                    }
                }
                chat.Print($"Now Playing: {artists} - {songname}");
            }
            else
            {
                chat.Print($"Not playing");
            }
        }
Esempio n. 5
0
        public async Task Play(RadioStation station)
        {
            if (!await App.CheckForOffline())
            {
                return;
            }
            if (station == null)
            {
                App.ShowAlert(Strings.RenameError, Strings.PleaseTryAgain);
                return;
            }
            LogManager.Shared.LogPlay(station);
            var online = station as OnlineRadioStation;

            if (online != null)
            {
                await MusicManager.Shared.AddTemp(online);
            }
            SendEndNotification(ScrobbleManager.PlaybackEndedReason.Skipped);
            var context = new PlaybackContext
            {
                IsContinuous = true,
                Type         = PlaybackContext.PlaybackType.Radio,
                ParentId     = station.Id
            };

            if (context.ParentId != "IFL" && context.Equals(Settings.CurrentPlaybackContext) && CurrentPlaylistSongCount > 0)
            {
                Play();
                return;
            }

            using (new Spinner(Strings.StartingStation))
            {
                Settings.CurrentPlaybackContext = context;
                var success = await MusicManager.Shared.LoadRadioStationTracks(station);

                if (!success)
                {
                    App.ShowAlert(Strings.RenameError, Strings.PleaseTryAgain);
                    return;
                }
            }

            if (Settings.CurrentPlaybackContext?.ParentId != station.Id)
            {
                return;
            }

            await Task.Run(async() =>
            {
                string query = $"select SongId as Id from RadioStationSong where StationId = ? order by SOrder";
                await SetupCurrentPlaylist(query, "", new[] { station.Id });
            });

            var song = GetSong(CurrentSongIndex);
            await NativePlayer.PlaySong(song);

            await PrepareNextTrack();
        }
Esempio n. 6
0
    // Use this for initialization
    void Start()
    {
        ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback;

        ImplicitGrantAuth();

        context = _spotify.GetPlayback();

        Debug.Log("Device Id: " + context.Device.Id);

        shuffleState = context.ShuffleState;

        repeatState = context.RepeatState;

        privateProfile = _spotify.GetPrivateProfile();

        Debug.Log(privateProfile.Country);

        audioVisualizer = GameObject.Find("AudioVisualizer");

        audioVisualizerScript = audioVisualizer.GetComponent <AudioVisualizer>();

        featuredPlaylistTabScript = FeaturedPlaylistTab.GetComponent <FeaturedPlaylistTabScript>();

        searchResultsScript = searchResultsTab.GetComponent <SearchResultsScript>();

        currentSongScript = CurrentSongGameObject.GetComponent <CurrentSong>();

        recordPlayerScript = recordPlayer.GetComponent <RecordPlayer>();

        //Ignore collisions between character controller and vinyls
        Physics.IgnoreLayerCollision(8, 9);

        OnClicked += SendAudioAnaylisToParticleVisualizer;
    }
Esempio n. 7
0
        private void Resume()
        {
            avaiability(async() =>
            {
                playback = await SpotifyApi.GetPlaybackAsync();

                if (playback.Context != null || playback.Item != null)
                {
                    if (playback.IsPlaying)
                    {
                        PlayerImage     = "ic_action_play.png";
                        ErrorResponse x = await SpotifyApi.PausePlaybackAsync();
                    }
                    else
                    {
                        PlayerImage     = "ic_action_pause.png";
                        ErrorResponse x = await SpotifyApi.ResumePlaybackAsync(playback.Device.Id, string.Empty,
                                                                               new List <string>()
                        {
                            playback.Item.Uri
                        }, "", playback.ProgressMs);
                    }
                }
            });
        }
Esempio n. 8
0
 public static void PausePlaySong()
 {
     try
     {
         using var _spotify = new SpotifyWebAPI()
               {
                   AccessToken = (string)App.Current.Properties["AccessToken"],
                   TokenType   = (string)App.Current.Properties["TokenType"]
               };
         PlaybackContext context = _spotify.GetPlayback();
         if (context.IsPlaying)
         {
             ErrorResponse error = _spotify.PausePlayback();
             App.Current.Properties["userPause"] = true;
         }
         else
         {
             ErrorResponse error = _spotify.ResumePlayback(offset: "");
             App.Current.Properties["userPause"] = false;
         }
     }
     catch
     {
         System.Diagnostics.Debug.WriteLine("Failed at Spotify/PausePlaySong");
     }
 }
Esempio n. 9
0
 public static int GetSetVolume(int volume = 255)
 {
     try
     {
         using var _spotify = new SpotifyWebAPI()
               {
                   AccessToken = (string)App.Current.Properties["AccessToken"],
                   TokenType   = (string)App.Current.Properties["TokenType"]
               };
         // Below should in theory work, but doesn't seem to
         PlaybackContext context = _spotify.GetPlayback();
         if (volume == 255)
         {
             return(context.Device.VolumePercent);
         }
         else
         {
             ErrorResponse _ = _spotify.SetVolume(volume);
             return(1);
         }
     }
     catch
     {
         System.Diagnostics.Debug.WriteLine("Failed at Spotify/GetSetVolume");
         return(-1);
     }
 }
Esempio n. 10
0
        // ReSharper disable ConstantConditionalAccessQualifier
        // ReSharper disable once ConstantNullCoalescingCondition
        public CurrentlyPlayingObject([NotNull] PlaybackContext playbackContext)
            : this(playbackContext?.ProgressMs ?? 0, playbackContext?.IsPlaying ?? false, null, SpotifyTrackType.Unknown)
        {
            if (playbackContext == null)
            {
                throw new ArgumentNullException(nameof(playbackContext));
            }

            switch (playbackContext.CurrentlyPlayingType)
            {
            case TrackType.Track:
                if (playbackContext.Item != null)
                {
                    this.Track = new Song(playbackContext.Item);
                }
                break;

            case TrackType.Episode:
                this.Track = new SpotifyTrack(SpotifyTrackType.Episode, playbackContext.Item?.Name, (playbackContext.Item?.DurationMs ?? 0) / 1000);
                break;

            case TrackType.Ad:
                this.Track = new SpotifyTrack(SpotifyTrackType.Ad);
                break;

            case TrackType.Unknown:
                this.Track = new SpotifyTrack(SpotifyTrackType.Unknown, playbackContext.Item?.Name, (playbackContext.Item?.DurationMs ?? 0) / 1000);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            this.Type = this.Track?.Type ?? SpotifyTrackType.Unknown;
        }
        protected async void Execute()
        {
            while (true)
            {
                Thread.Sleep(30000);
                PlaybackContext Context = await Api.GetPlayingTrackAsync();

                if (!Context.HasError() && Context.IsPlaying && IsNotAd(Context))
                {
                    List <string> Artists = new List <string>();
                    Context.Item.Artists.ForEach(Artist => Artists.Add(Artist.Name));
                    string SlackMessage = String.Format("Listening To: {0} by {1} ({2})",
                                                        Context.Item.Name,
                                                        String.Join(", ", Artists),
                                                        Context.Item.Album.Name);

                    string UserId = Environment.GetEnvironmentVariable("SPLACK_SLACK_USER_ID");

                    JObject Profile = new JObject();
                    Profile["status_text"]       = SlackMessage;
                    Profile["status_emoji"]      = ":notes:";
                    Profile["status_expiration"] = (long)DateTimeOffset.Now.ToUnixTimeSeconds() + ((Context.Item.DurationMs - Context.ProgressMs) / 1000);

                    Dictionary <string, string> Values = new Dictionary <string, string>
                    {
                        { "user", UserId },
                        { "profile", Profile.ToString() }
                    };

                    FormUrlEncodedContent Content  = new FormUrlEncodedContent(Values);
                    HttpResponseMessage   Response = await SlackClient.PostAsync("https://slack.com/api/users.profile.set", Content);
                }
            }
        }
Esempio n. 12
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Get the selected track info
            TrackInfo ti = ArtistListBox.SelectedItem as TrackInfo;

            // If the track info is good, play it (or pause if playing)
            if (ti == null)
            {
                return;
            }

            ErrorResponse   err      = null;
            PlaybackContext playback = _spotify.GetPlayback();

            if (_trackIsPlaying)
            {
                err = _spotify.PausePlayback();
            }
            else
            {
                List <string> trackUris = new List <string> {
                    "spotify:track:" + ti.TrackId
                };
                err = _spotify.ResumePlayback(deviceId: _spotifyPlaybackDevice, contextUri: "", uris: trackUris, offset: "", positionMs: 0);
            }

            if (err?.Error?.Status != 0)
            {
                _trackIsPlaying = !_trackIsPlaying;
            }
            else
            {
                // TODO: evaluate error
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Displays the current song being played from Spotify
        /// </summary>
        /// <param name="chatter">User that sent the message</param>
        public static async Task <string> SpotifyCurrentSongAsync(TwitchChatter chatter, SpotifyWebClient spotify)
        {
            PlaybackContext playbackContext = await spotify.GetPlaybackAsync();

            if (playbackContext != null && playbackContext.IsPlaying)
            {
                string artistName = "";

                foreach (SimpleArtist simpleArtist in playbackContext.Item.Artists)
                {
                    artistName += $"{simpleArtist.Name}, ";
                }

                artistName = artistName.ReplaceLastOccurrence(", ", "");

                TimeSpan progressTimeSpan = TimeSpan.FromMilliseconds(playbackContext.ProgressMs);
                TimeSpan durationTimeSpan = TimeSpan.FromMilliseconds(playbackContext.Item.DurationMs);

                return($"@{chatter.DisplayName} <-- Now playing from Spotify: \"{playbackContext.Item.Name}\" by {artistName} "
                       + "https://open.spotify.com/track/" + playbackContext.Item.Id + " "
                       + $"Currently playing at {progressTimeSpan.ReformatTimeSpan()} of {durationTimeSpan.ReformatTimeSpan()}");
            }
            else
            {
                return($"Nothing is playing at the moment @{chatter.DisplayName}");
            }
        }
Esempio n. 14
0
        internal static PlaybackResponse MapContext(this PlaybackContext context)
        {
            if (context == null)
            {
                return(new PlaybackResponse("Could not reach Spotify services"));
            }

            if (context.HasError())
            {
                return(new PlaybackResponse(context.Error.Message));
            }

            if (context.Item == null)
            {
                return(new PlaybackResponse("Could not find a playable device/track"));
            }

            return(new PlaybackResponse(
                       isPlaying: context.IsPlaying,
                       progress: context.ProgressMs,
                       track: new Track(
                           name: context.Item.Name,
                           artist: string.Join(", ", context.Item.Artists.Select(artist => artist.Name)),
                           album: context.Item.Album.Name,
                           albumArt: context.Item.Album.Images.FirstOrDefault()?.Url,
                           duration: context.Item.DurationMs)));
        }
Esempio n. 15
0
 private void trackChanged(object sender, AudioChangeArgs e)
 {
     if (e.getPlayback().Item != null)
     {
         PlaybackContext track = e.getPlayback();
         pictureBox1.Load(track.Item.Album.Images[0].Url);
         WriteTextSafe(track.Item.Name);
         try
         {
             ArduinoInterface.sendFromImageUrl(track.Item.Album.Images[0].Url);
             ArduinoInterface.sendPlay(track.ProgressMs * 1000, track.Item.DurationMs * 1000);
         }
         catch (Exception ee)
         {
             RefreshButton.Visible = true;
         }
     }
     else
     {
         pictureBox1.Image = Properties.Resources.NoSong;
         WriteTextSafe("No Song Playing");
         try {
             ArduinoInterface.sendImage(Properties.Resources.NoSong);
             ArduinoInterface.sendPause(0, 0);
         }
         catch (Exception ee)
         {
             RefreshButton.Visible = true;
         }
     }
 }
Esempio n. 16
0
    public void PlayURIThread(string playlistURI)
    {
        PlaybackContext context = _spotify.GetPlayback();

        if (context.Device == null || context.Device.Id == null || context.Device.Id == "")
        {
            Debug.LogError("Invalid device");
            return;
        }
        else
        {
            Debug.Log("In PlayURIThread, have gotten spotify playback, device id is " + context.Device.Id);
        }

        //    float before = Time.realtimeSinceStartup;
        ErrorResponse error = _spotify.ResumePlayback(context.Device.Id, playlistURI);

        //     Debug.Log("Time taken to play URI: " + (Time.realtimeSinceStartup - before));

        if (error.Error != null)
        {
            Debug.LogError(error.Error.Message);
            Debug.LogError(error.Error.Status);
            Debug.LogError(playlistURI);
        }
    }
Esempio n. 17
0
    public void PausePlaybackThread()
    {
        PlaybackContext context = _spotify.GetPlayback();

        if (context.Device == null || context.Device.Id == null || context.Device.Id == "")
        {
            Debug.LogError("Invalid device");
            return;
        }
        else
        {
            Debug.Log("In PausePlaybackThread, have gotten spotify playback, device id is " + context.Device.Id);
        }

        if (context.IsPlaying)
        {
            ErrorResponse error = _spotify.PausePlayback(context.Device.Id);
            audioVisualizerScript.repeat = false;

            if (error.Error != null)
            {
                Debug.LogError(error.Error.Status);
                Debug.LogError(error.Error.Message);
            }
        }
        //   pausePlaybackRunning = false;
    }
Esempio n. 18
0
    public void PlaySongURIThread(string songURI)
    {
        Debug.Log("In PlaySongUriThread");

        PlaybackContext context = _spotify.GetPlayback();


        if (context.Device == null || context.Device.Id == null || context.Device.Id == "")
        {
            Debug.LogError("Invalid device");
            threadRunning = false;
            return;
        }
        else
        {
            Debug.Log("In PlaySongUriThread, have gotten spotify playback, device id is " + context.Device.Id);
        }

        ErrorResponse error = _spotify.ResumePlayback(context.Device.Id, uris: new List <string> {
            songURI
        });

        Debug.Log("Spotify Resume Playback has been called");

        if (error.HasError())
        {
            Debug.LogError(error.Error.Message);
            Debug.LogError(error.Error.Status);
        }

        threadRunning = false;
    }
Esempio n. 19
0
    public void SkipPlaybackToPreviousThread()
    {
        PlaybackContext context = _spotify.GetPlayback();

        if (context.Device == null || context.Device.Id == null || context.Device.Id == "")
        {
            Debug.LogError("Invalid device");
            return;
        }
        else
        {
            Debug.Log("In SkipPlaybackToNext, have gotten spotify playback, device id is " + context.Device.Id);
        }

        if (context.IsPlaying)
        {
            ErrorResponse error = _spotify.SkipPlaybackToPrevious();

            if (error.Error != null)
            {
                Debug.LogError(error.Error.Message);
            }
        }
        else
        {
            Debug.Log("Can't skip playback to previous if not currently playing");
        }

        //    skipPlaybackToPreviousRunning = false;
    }
Esempio n. 20
0
        public JsonResult NowPlaying()
        {
            Dictionary <string, string> nowPlaying = new Dictionary <string, string>();

            if (User.Identity.IsAuthenticated)
            {
                string accessToken = HttpContext.GetTokenAsync("access_token").Result;

                try
                {
                    // For usage visit: https://github.com/JohnnyCrazy/SpotifyAPI-NET/
                    SpotifyWebAPI spotifyAPI = new SpotifyWebAPI
                    {
                        AccessToken = accessToken,
                        TokenType   = "Bearer"
                    };

                    PrivateProfile  profile = spotifyAPI.GetPrivateProfileAsync().Result;
                    PlaybackContext context = spotifyAPI.GetPlayback();
                    if (!profile.HasError())
                    {
                        nowPlaying.Add("SpotifyName", profile.DisplayName);
                        nowPlaying.Add("SpotifyAvatar", profile.Images.FirstOrDefault().Url);
                        nowPlaying.Add("SpotifyProfileUrl", "https://open.spotify.com/user/" + profile.Id);
                    }

                    if (context.Item != null && (context.IsPlaying))
                    {
                        nowPlaying.Add("SongName", context.Item.Name);
                        nowPlaying.Add("SongUrl", context.Item.Href);
                        nowPlaying.Add("ArtistName", context.Item.Artists.FirstOrDefault().Name);
                        nowPlaying.Add("ArtistUrl", context.Item.Artists.FirstOrDefault().Href);
                        nowPlaying.Add("NowPlaying", nowPlaying["SongName"] + " by " + nowPlaying["ArtistName"]);
                        nowPlaying.Add("AlbumArt", context.Item.Album.Images.FirstOrDefault().Url);
                        nowPlaying.Add("AlbumUrl", context.Item.Album.ExternalUrls["spotify"]);
                        nowPlaying.Add("IsPlaying", "true");
                    }
                    else
                    {
                        nowPlaying.Add("SongName", null);
                        nowPlaying.Add("SongUrl", null);
                        nowPlaying.Add("ArtistName", null);
                        nowPlaying.Add("ArtistUrl", null);
                        nowPlaying.Add("NowPlaying", null);
                        nowPlaying.Add("AlbumArt", null);
                        nowPlaying.Add("AlbumUrl", null);
                        nowPlaying.Add("IsPlaying", "false");
                    }
                    GeniusService geniusService = new GeniusService(nowPlaying["SongName"], nowPlaying["ArtistName"]);
                    nowPlaying.Add("Lyrics", geniusService.Lyrics);
                    nowPlaying.Add("LyricsContribution", geniusService.Url);
                }
                catch (Exception ex)
                {
                    // show the users some error
                }
            }
            return(new JsonResult(nowPlaying));
        }
Esempio n. 21
0
        public HoldEffectBinding(PlaybackContext playbackContext, ObjectReference attachedObject) : base(playbackContext)
        {
            AttachedObject = attachedObject;
            CreateEffect(playbackContext.Playback.Beatmap.GetEffectSettings(Hold.EffectType));

            // Apply object parameters to hold note effect
            EffectState.ApplyObjectParameters(attachedObject);
        }
Esempio n. 22
0
        public RockolappScreenData GetCurrentTrack(string spotifyUserId)
        {
            string token;

            var user = dataAccess.GetUser(spotifyUserId);

            var spotify = new SpotifyWebAPI()
            {
                TokenType   = "Bearer",
                AccessToken = user.Token,
                UseAuth     = true
            };

            PlaybackContext context = spotify.GetPlayingTrack();


            if (context.HasError() && context.Error.Status == 401)
            {
                AutorizationCodeAuth auth = new AutorizationCodeAuth();

                //Datos de mi aplicacion Rocolapp
                auth.ClientId    = DataAccess.GetRocolappData().ClientId;
                auth.RedirectUri = DataAccess.GetRocolappData().RedirectUri;
                string clientSecret = DataAccess.GetRocolappData().ClientSecret;

                Token newToken = auth.RefreshToken(user.RefreshToken, DataAccess.GetRocolappData().ClientSecret);


                dataAccess.UpdateToken(user.Id.ToString(), newToken.AccessToken);

                token = newToken.AccessToken;

                var withRefreshedToken = new SpotifyWebAPI()
                {
                    TokenType   = "Bearer",
                    AccessToken = newToken.AccessToken,
                    UseAuth     = true
                };

                context = withRefreshedToken.GetPlayingTrack();
            }

            RockolappScreenData screenData = new RockolappScreenData();

            try
            {
                screenData.TrackName  = context.Item.Name;
                screenData.Artist     = context.Item.Artists.First().Name;
                screenData.Duration   = context.Item.DurationMs;
                screenData.LapsedTime = context.ProgressMs;
                screenData.ImageUrl   = context.Item.Album.Images.First().Url;
            }
            catch (Exception)
            {
            }

            return(screenData);
        }
Esempio n. 23
0
        private void CheckEventCallback(
            ICollection <EventToSend> eventsToSend,
            ICollection <ReceivedEvent> expectedReceivedEvents,
            TimeSpan changeCallbackAfter,
            EventCallback eventCallback,
            EventCallback secondEventCallback)
        {
            var playbackContext = new PlaybackContext();

            var receivedEvents = playbackContext.ReceivedEvents;
            var sentEvents     = playbackContext.SentEvents;
            var stopwatch      = playbackContext.Stopwatch;
            var tempoMap       = playbackContext.TempoMap;

            var eventsForPlayback = GetEventsForPlayback(eventsToSend, tempoMap);

            var notesStarted  = new List <Note>();
            var notesFinished = new List <Note>();

            using (var outputDevice = OutputDevice.GetByName(SendReceiveUtilities.DeviceToTestOnName))
            {
                SendReceiveUtilities.WarmUpDevice(outputDevice);
                outputDevice.EventSent += (_, e) => sentEvents.Add(new SentEvent(e.Event, stopwatch.Elapsed));

                using (var playback = new Playback(eventsForPlayback, tempoMap, outputDevice))
                {
                    playback.NotesPlaybackStarted  += (_, e) => notesStarted.AddRange(e.Notes);
                    playback.NotesPlaybackFinished += (_, e) => notesFinished.AddRange(e.Notes);

                    playback.EventCallback = eventCallback;

                    using (var inputDevice = InputDevice.GetByName(SendReceiveUtilities.DeviceToTestOnName))
                    {
                        inputDevice.EventReceived += (_, e) =>
                        {
                            lock (playbackContext.ReceivedEventsLockObject)
                            {
                                receivedEvents.Add(new ReceivedEvent(e.Event, stopwatch.Elapsed));
                            }
                        };

                        inputDevice.StartEventsListening();
                        stopwatch.Start();
                        playback.Start();

                        SpinWait.SpinUntil(() => stopwatch.Elapsed >= changeCallbackAfter);
                        playback.EventCallback = secondEventCallback;

                        var timeout         = TimeSpan.FromTicks(eventsToSend.Sum(e => e.Delay.Ticks)) + SendReceiveUtilities.MaximumEventSendReceiveDelay;
                        var playbackStopped = SpinWait.SpinUntil(() => !playback.IsRunning, timeout);
                        Assert.IsTrue(playbackStopped, "Playback is running after completed.");
                    }
                }
            }

            CompareReceivedEvents(receivedEvents, expectedReceivedEvents.ToList());
        }
Esempio n. 24
0
        public async Task PausePlayback()
        {
            PlaybackContext context = await api.GetPlaybackAsync();

            if (context.IsPlaying)
            {
                await api.PausePlaybackAsync();
            }
        }
Esempio n. 25
0
        public async Task ResumePlayback()
        {
            PlaybackContext context = await api.GetPlaybackAsync();

            if (context.IsPlaying == false)
            {
                await api.ResumePlaybackAsync("", "", null, "", 0);
            }
        }
Esempio n. 26
0
 public void Refresh(PlaybackContext playback)
 {
     if (playback?.HasError() == false && playback.Item?.HasError() == false &&
         playback.ProgressMs != currentTime)
     {
         TrackTimeChanged?.Invoke(new TrackTimeInfo((uint)playback.ProgressMs, (uint)playback.Item.DurationMs));
         currentTime = playback.ProgressMs;
     }
 }
Esempio n. 27
0
        public static void Main(string[] args)
        {
            string artistName = string.Empty;
            string trackName  = string.Empty;

            try
            {
                PlaybackContext pc = Spotify.GetPlayback();
                if (pc == null)
                {
                    throw new Exception("PlaybackContext null");
                }

                if (pc.Error != null)
                {
                    throw new Exception($"{pc.Error.Status} - {pc.Error.Message}");
                }

                if (pc.Item == null)
                {
                    throw new Exception("FullTrack null");
                }

                artistName = pc.Item.Artists?.FirstOrDefault()?.Name;
                trackName  = pc.Item.Name;
                foreach (ILyrics lyrics in LyricsWebsites)
                {
                    string lyricsResult = lyrics.SearchLyricsUrl(artistName, trackName);
                    if (string.IsNullOrWhiteSpace(lyricsResult))
                    {
                        continue;
                    }

                    Process.Start(lyricsResult);
                    return;
                }

                MessageBox.Show($"Artist: {artistName}\nTrack: {trackName}", "Lyrics not found");
            }
            catch (Exception e)
            {
                if (EhDebug)
                {
                    throw;
                }

                string message = e.ToString();
                if (!string.IsNullOrWhiteSpace(artistName) || !string.IsNullOrWhiteSpace(trackName))
                {
                    message = $"Artist: {artistName}\nTrack: {trackName}\n{message}";
                }

                Trace.TraceError(message);
                MessageBox.Show(message, "Exception");
            }
        }
Esempio n. 28
0
        public static void ChangePlayback(SpotifyWebAPI api, FullPlaylist playlist)
        {
            String          UriTrack = GetUriRandom(api, playlist);
            PlaybackContext play     = api.GetPlayingTrack();

            api.SetVolume(50);


            api.ResumePlayback(deviceId: "", contextUri: playlist.Uri, uris: null, offset: "");
        }
Esempio n. 29
0
        private void CheckTrackControlValueWithOutputDevice(
            ICollection <EventToSend> eventsToSend,
            ICollection <EventToSend> eventsWillBeSent,
            TimeSpan moveFrom,
            TimeSpan moveTo)
        {
            var playbackContext = new PlaybackContext();

            var receivedEvents = playbackContext.ReceivedEvents;
            var sentEvents     = playbackContext.SentEvents;
            var stopwatch      = playbackContext.Stopwatch;
            var tempoMap       = playbackContext.TempoMap;

            var eventsForPlayback = GetEventsForPlayback(eventsToSend, tempoMap);
            var notes             = eventsForPlayback.GetNotes().ToArray();

            using (var outputDevice = OutputDevice.GetByName(SendReceiveUtilities.DeviceToTestOnName))
            {
                SendReceiveUtilities.WarmUpDevice(outputDevice);
                outputDevice.EventSent += (_, e) => sentEvents.Add(new SentEvent(e.Event, stopwatch.Elapsed));

                using (var playback = new Playback(eventsForPlayback, tempoMap, outputDevice))
                {
                    playback.TrackControlValue = true;

                    using (var inputDevice = InputDevice.GetByName(SendReceiveUtilities.DeviceToTestOnName))
                    {
                        inputDevice.EventReceived += (_, e) =>
                        {
                            lock (playbackContext.ReceivedEventsLockObject)
                            {
                                receivedEvents.Add(new ReceivedEvent(e.Event, stopwatch.Elapsed));
                            }
                        };
                        inputDevice.StartEventsListening();
                        stopwatch.Start();
                        playback.Start();

                        SpinWait.SpinUntil(() => stopwatch.Elapsed >= moveFrom);
                        playback.MoveToTime((MetricTimeSpan)moveTo);

                        var timeout           = TimeSpan.FromTicks(eventsWillBeSent.Sum(e => e.Delay.Ticks)) + SendReceiveUtilities.MaximumEventSendReceiveDelay;
                        var areEventsReceived = SpinWait.SpinUntil(() => receivedEvents.Count == eventsWillBeSent.Count, timeout);
                        Assert.IsTrue(areEventsReceived, $"Events are not received for timeout {timeout}.");

                        stopwatch.Stop();

                        var playbackStopped = SpinWait.SpinUntil(() => !playback.IsRunning, SendReceiveUtilities.MaximumEventSendReceiveDelay);
                        Assert.IsTrue(playbackStopped, "Playback is running after completed.");
                    }
                }
            }

            CompareSentReceivedEvents(sentEvents, receivedEvents, eventsWillBeSent.ToList());
        }
Esempio n. 30
0
        public static async Task <bool> AddHistoryToDatabase(PlaybackContext data, string userId)
        {
            using (var db = new AiApiDbContext())
            {
                try
                {
                    var fullTrack = new dFullTrack
                    {
                        Id          = data.Item.Id,
                        Explicit    = data.Item.Explicit,
                        Name        = data.Item.Name,
                        PreviewUrl  = data.Item.PreviewUrl,
                        TrackNumber = data.Item.TrackNumber,
                        Uri         = data.Item.Uri,
                        Type        = data.Item.Type
                    };

                    if (data.Item.Artists.Any())
                    {
                        fullTrack.Artist1Id = data.Item.Artists[0].Id;

                        if (data.Item.Artists.Count > 1)
                        {
                            fullTrack.Artist2Id = data.Item.Artists[1].Id;
                        }
                    }

                    //let's make sure we don't already have the song in here
                    if (!db.Songs.Any(s => s.Name == fullTrack.Name && s.Artist1Id == fullTrack.Artist1Id))
                    {
                        //add the track to query
                        db.Songs.Add(fullTrack);
                    }

                    //then we'll grab the instance of it.
                    var playHistory = new dPlayHistory
                    {
                        PrivateProfile    = db.PrivateProfiles.SingleOrDefault(x => x.Id == userId),
                        PrivateProfilesId = userId,
                        Name     = data.Item.Name,
                        PlayedAt = DateTime.Now,
                        TrackId  = data.Item.Id
                    };

                    db.RecentlyPlayed.Add(playHistory);

                    await db.SaveChangesAsync();
                }
                catch (Exception ex)
                {
                    return(false);
                }
                return(true);
            }
        }