Getting Spotify Song ID with Spotify API in C# menu

User Tag List

Results 1 to 1 of 1
  1. #1
    Veritable's Avatar OwnedCore News Correspondent
    Reputation
    326
    Join Date
    Apr 2007
    Posts
    372
    Thanks G/R
    52/123
    Trade Feedback
    0 (0%)
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Getting Spotify Song ID with Spotify API in C#

    Hello there fellow programmers!

    So today's topic is the Spotify API. The language we'll be using is C# and I am going to go over the absolute basics of getting a Song ID from the API provided via the Spotify Developer's center.

    First step, is you are going to need a Client ID and Client Secret for your application. So proceed to My Dashboard | Spotify for Developers and register your application.

    Once you have these values, you can continue on with the program itself, and will only need to use that site to see statistics of usage of the app. Whenever you do a query using your client ID and secret, it will count as a hit on the site, thus track usage.

    The Spotify API uses OAuth2 method of tokens, and as such there are 3 different types of tokens (as listed on their guides page: Authorization Guide | Spotify for Developers )

    All responses from the API are in Json so you are going to want to use your favorite flavor of reading and parsing Json inside of C#. So lets start off by creating a class from the Json response when we request a token, so that we can just simply deserialize it and make our lives simpler.

    Code:
            public class SpotifyToken {
                public string Access_token { get; set; }
                public string Token_type { get; set; }
                public int Expires_in { get; set; }
            }
    Now we can create a function to request the actual token from the servers. Somewhere in here, you will need to provide your client_id and client_secret strings. You can do it inside here, or in a config file, perhaps even a public variable somewhere, that's your choice.

    Code:
           public string GetAccessToken() {
                SpotifyToken token = new SpotifyToken();
                string url5 = "https://accounts.spotify.com/api/token";
    
    
                var encode_clientid_clientsecret = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", clientid, clientsecret)));
    
    
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url5);
    
    
                webRequest.Method = "POST";
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.Accept = "application/json";
                webRequest.Headers.Add("Authorization: Basic " + encode_clientid_clientsecret);
    
    
                var request = ("grant_type=client_credentials");
                byte[] req_bytes = Encoding.ASCII.GetBytes(request);
                webRequest.ContentLength = req_bytes.Length;
    
    
                Stream strm = webRequest.GetRequestStream();
                strm.Write(req_bytes, 0, req_bytes.Length);
                strm.Close();
    
    
                HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
                String json = "";
                using (Stream respStr = resp.GetResponseStream()) {
                    using (StreamReader rdr = new StreamReader(respStr, Encoding.UTF8)) {
                        //should get back a string i can then turn to json and parse for accesstoken
                        json = rdr.ReadToEnd();
                        rdr.Close();
                    }
                }
                token = JsonConvert.DeserializeObject<SpotifyToken>(json);
                return token.Access_token;
            }
    So this class will request a token, and return the string value. So now you can just request this token when you need it, and it has an expiry of 3600ms. So if you request a token, and 3601 ms have gone past, you will need to re-request a token, or implement an auto-refresh token system, which is not covered here.

    Now we are going to take this token, and use it to request a song ID.

    Code:
            private string GetTrackInfo(string url) {
                string webResponse = string.Empty;
                myToken = GetAccessToken();
                try {
                    // Get token for request
                    HttpClient hc = new HttpClient();
                    var request = new HttpRequestMessage() {
                        RequestUri = new Uri(url),
                        Method = HttpMethod.Get
                    };
                    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    request.Headers.Authorization = new AuthenticationHeaderValue("Authorization", "Bearer " + myToken);
                    // TODO: Had a task cancelled here, too many errors. Find a better way to process this maybe.
                    // Same code is in GetTrackFeatures function.
                    var task = hc.SendAsync(request)
                        .ContinueWith((taskwithmsg) => {
                            var response = taskwithmsg.Result;
                            var jsonTask = response.Content.ReadAsStringAsync();
                            webResponse = jsonTask.Result;
                        });
                    task.Wait();
    
    
                } catch (WebException ex) {
                    Console.WriteLine("Track Request Error: " + ex.Status);
                } catch (TaskCanceledException tex) {
                    Console.WriteLine("Track Request Error: " + tex.Message);
                }
                return webResponse;
            }
    In this function, we send the request using a URL that is pretty straight forward, but here is what it looks like with an example:

    Code:
    string trackTitle = "Back In Black";
    string trackArtist = "ACDC";
    string url = string.Format("https://api.spotify.com/v1/search?q={0} {1}&type=track&market=US&limit=10&offset=0",trackTitle,trackArtist);
    then we just call the function and it will return the Json response for us to parse in whatever way desired.

    Code:
    var jsonData = GetTrackInfo(url);
    In that search query, the limit is 10 tracks, which means that it is going to send you a bunch of tracks, and it will be up to you on how to determine what track you actually want. If you are using properly ID'd songs, you can pull the Album out of the track and try to match all results with said album and return that song id.

    In my case, I did a simple 'popularity' check. So I return the most popular track with a simple foreach loop.

    Code:
                string id = "";
                int popularity = 0;
    
    
                TrackInfoObject tList = JsonConvert.DeserializeObject<TrackInfoObject>(result);
                if (tList.tracks == null) {
                    //Console.WriteLine("Cannot Retrieve Song: {0} - {1} : {2}", trackArtist, trackTitle, fileName);
                } else {
                    foreach (Item t in tList.tracks.items) {
                        if (id == "") {
                            id = t.id;
                            popularity = t.popularity;
                        } else {
                            if (t.popularity > popularity) {
                                id = t.id;
                                popularity = t.popularity;
                            }
                        }
                    }
                }
    Now if you are wondering, that TrackInfoObject is a class that is made with json2csharp using the json returned sample when I did a search in the web console inside of the Spotify Dashboard. I used the test result to get what I needed as a result, and copied the json into their tool, renamed the RootObject to TrackInfoObject and voila. Now you can deserialize the json response to an easily referenced class.

    Hope this helps someone with their code base. I got my software working to this point, so now it's time to work it into the actual server for Auditory Disruption. To follow it's development, go ahead and follow this thread: https://www.ownedcore.com/forums/gen...os-future.html (Auditory Disruption - Remote Audio Streaming App (Android / PC / iOS in the future))

    Getting Spotify Song ID with Spotify API in C#
  2. Thanks sed-, Willy (2 members gave Thanks to Veritable for this useful post)

Similar Threads

  1. [Release] Start with all items in slot id's (Tier 7 and more)
    By cosminelu16 in forum WoW EMU General Releases
    Replies: 17
    Last Post: 07-31-2009, 10:27 PM
  2. get out of combat with patrolling birds in skettis
    By inspiteofmyself in forum World of Warcraft Exploits
    Replies: 6
    Last Post: 11-08-2008, 05:39 PM
  3. Get triple XP buff with a level 1 in high level area!
    By bagsnatcher in forum World of Warcraft Exploits
    Replies: 25
    Last Post: 08-11-2008, 12:14 PM
  4. Replies: 18
    Last Post: 07-30-2008, 11:42 AM
All times are GMT -5. The time now is 11:56 AM. Powered by vBulletin® Version 4.2.3
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved. User Alert System provided by Advanced User Tagging (Pro) - vBulletin Mods & Addons Copyright © 2024 DragonByte Technologies Ltd.
Digital Point modules: Sphinx-based search