Nokia Music API

    Recently, at the MWC-2013 conference, we presented our new phones. In addition, another news was voiced, which is important primarily for software developers. We are opening new APIs for third-party developers: Photo API, Nokia Music API and Maps API. Today we talk about the Nokia Music Windows Phone API . Nokia Music Windows Phone API provides the application with easy access to the latest information on millions of tracks from all over the globe.





    Thanks to the Nokia Music Windows Phone API, an application can get a number of important advantages:
    • Coverage.
    • Simplification.
    • API contracts "bottom-up compatible."

    Reach:
    • helps users search for music of interest to them;
    • provides detailed information about the piece of music that the user is interested in.
    • Allows access to approximately 200 million tracks in more than 200 countries from almost 3 million local and international artists.

    Simplification of application development:
    The main task of Music Api is to collect and, more importantly, maintain the relevance of facts about tens of millions of tracks from record labels and aggregators. Without it, you would have to spend a lot of time in order to collect, verify, standardize and ensure the relevance of this data.

    API compatibility:
    The Music REST API API contract is designed with a simple fact in mind - you can always learn something new about music.
    The API contract allows you to add additional elements at any time without having to introduce a new version of the API contract. But more importantly, if you follow the instructions and recommendations described in this article, you don’t have to release a new version of the application, its users will automatically gain access to new features.

    Let's look at the capabilities of the API using the example of the Music Explorer application.

    You can download the application itself and its source code here: link .
    Music Explorer demonstrates how to use the Nokia Music API with the standard audio features of Windows Phone 8. The application uses features of the Nokia Music API, such as searching by artist name, requesting top artists and new releases, and launching Nokia Music from another application to play “ Mix Radio ”or view artist or song information.

    Unlike browsers like Nokia Music Lite, the Music Music interface interacts with music on your device in a variety of ways to view artists and music Explorer songs using the Nokia Music API. Favorite artists are sorted by listening frequency, the list of recommended artists is sorted according to the number of matches with the Favorites list. In addition, you can listen to tracks stored on the device.

    Design and interface:
    The main Panorama of Music Explorer, shown below, contains six items: Favorites, Recommended, New, Top, Genres and Mixes. Click image to enlarge

    image



    Favorites shows 20 artists whose songs are most often played on the device, as well as their images obtained using the Nokia Music API. “Recommended” offers a list of the most similar artists sorted by a similar criterion. “Novelties” and “Top” show the last 10 songs and the top 10 artists from the Nokia Music service. Genres and Mixes also display the corresponding lists from Nokia Music. The list of genres and mixes depends on the current country of residence, and their names are given in the corresponding language. For this, the service uses the location data of the device.

    Another major user interface component is the executor block, shown below. You can get into it by choosing an artist from the "Favorites", "Recommended", the list of "top 10" or the list of genres. The artist block is used to view the products available in the Nokia Music service for a specific artist. You cannot purchase products using the Nokia Music API, therefore, in this case, the Nokia Music application opens, in which you can buy the selected track. Also, the artist’s block allows you to start the mix of this artist in Nokia Music or listen to his tracks stored on the device.



    Nokia Music Api can be used to launch the Nokia Music service from another application. A service can be launched on the tab for viewing a specific artist or song (mix, track, album or single). In addition, you can start the service already on playing the selected mix. The “note” symbol is displayed in Music Explorer if interacting with the marked object will launch Nokia Music. Below are the pages "Genres" and "Mixes" that open at the choice of the user.



    Architecture and implementation:
    Music Explorer is a simple application that implements the model - view - view model (MVVM) template. This template allows you to separate data and user interface and is widely used when developing applications for Windows Phone 8. In the application, the model (data) is C # classes, and the view (user interface) is a set of PhoneApplicationPages populated using WP8 controls. MainViewModel, which connects models and views, is also a C # class. It is set as a DataContext for all application pages to provide data binding. You can learn more about MVVM here , as well as using the list of links in the See Also section at the bottom of the page. To view a more detailed architectural description of Music Explorer, you can visit the Implementation page.this project on the wiki.

    Here is a table of the most significant APIs used by Music Explorer, as well as their capabilities:



    The following Music Explorer services are provided by the Nokia Music API:



    To use the Nokia Music API, an application will need a unique app ID and app token (if you are not going to use only launchers). They can be obtained by registering on the API registration page and requesting credentials for the Nokia Music API. The App ID and app token for Music Explorer are listed in MusicApi.cs:

    namespace MusicExplorer
    {
        ...
        public class MusicApi
        {
            // Constants
            public const string MUSIC_EXPLORER_APP_ID = "music_explorer_private_app_id"; // real app id not shown here
            public const string MUSIC_EXPLORER_APP_TOKEN = "music_explorer_private_app_token"; // real app token not shown here
            ...
        }
    }
    


    The application for WP8 should also have links to the current Nokia Music API client, which, in turn, requires a link to the JSON.Net library to add it to the application.
    Instructions for adding the necessary links are in the release_notes.txt file in the source files of the Music Explorer project .

    Localization of Nokia Music API:
    Before making a request to the Nokia Music API, Music Explorer checks the availability of the Nokia Music service for a specific country, which is implemented using the Windows Phone Location API. By default, the Nokia Music API uses (and checks) the region settings on the phone with every request to the API. This allows the user to receive relevant, partially translated and country-based information. This can be seen in the panorama image above, showing the genres and mixes available for Finland, as well as the top Finnish artists at the moment. This list will look different if you use a different valid country code when calling the Nokia Music API (for example, de for Germany or gb for the UK).

    using Nokia.Music.Phone;
    ...
    namespace MusicExplorer
    {
        ...
        public partial class MainPage : PhoneApplicationPage
        {
            ...
            private CountryResolver resolver = null;
            ...
            private void InitializeNokiaMusicApi(string twoLetterCountryCode)
            {
                if (resolver == null)
                {
                    resolver = new CountryResolver(MusicApi.MUSIC_EXPLORER_APP_ID,
                                                   MusicApi.MUSIC_EXPLORER_APP_TOKEN);
                }
                resolver.CheckAvailability((Response response) =>
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        if (response.Result)
                        {
                            // Make initial requests to fill models.
                            App.MusicApi.Initialize(twoLetterCountryCode);
                            ...
                        }
                        else
                        {
                            MessageBox.Show("Sorry, Nokia Music is not available in this locale.");
                        }
                   });
                },
                twoLetterCountryCode.ToLower());
            }
        }
    }
    


    Creating a client:
    In Music Explorer, communication with the Nokia Music API, with the exception of the use of CountryResolver described above, is enclosed in the MusicApi class for easy reference. All requests to the Nokia Music service are made using the MusicClient class, and so the next step after confirming the availability of the Nokia Music service is to create a MusicClient in the Initialize MusicApi method.

    using Nokia.Music.Phone;
    using Nokia.Music.Phone.Types;
    ...
    namespace MusicExplorer
    {
        ...
        public class MusicApi
        {
            ...
            // Members
            private MusicClient client = null;
            private bool initialized = false;
            ...
            public void Initialize(string countryCode)
            {
                // Create a music client with correct AppId and Token/AppCode
                if (countryCode == null || countryCode.Length != 2)
                {
                    client = new MusicClient(MUSIC_EXPLORER_APP_ID,
                                             MUSIC_EXPLORER_APP_TOKEN); 
                }
                else
                {
                    client = new MusicClient(MUSIC_EXPLORER_APP_ID,
                                             MUSIC_EXPLORER_APP_TOKEN,
                                             countryCode.ToLower());
                }
                initialized = true; 
            }
            ...
        }
    }


    Making requests:
    Requests to the Nokia Music service can be sent after creating a localized MusicClient example. For example, the GetTopArtists method from MusicApi requests the 10 most popular artists in the Nokia Music service (for the country with the code of which MusicClient was launched) and fills the TopArtists from MainViewModel with relevant information. The Who's in the Top panorama uses links to display TopArtists in the user interface. Since the remaining requests (new releases, genres, etc.) are similar, we will not consider them separately. You can look at the project page for links to specific examples.

    namespace MusicExplorer
    {
        ...
        public class MusicApi
        {
            ...
            // Members
            private MusicClient client = null;
            private bool initialized = false;
            ...
            public void GetTopArtists()
            {
                if (!initialized)
                {
                    return;
                }
                client.GetTopArtists((ListResponse response) =>
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        // Use results
                        if (response != null && response.Result != null && response.Result.Count > 0)
                        {
                            App.ViewModel.TopArtists.Clear();
                            foreach (Artist a in response.Result)
                            {
                                if (a.Thumb100Uri != null)
                                {
                                    App.ViewModel.TopArtists.Add(new ArtistModel()
                                         {
                                             Name = a.Name,
                                             Country = CountryCodes.CountryNameFromTwoLetter(a.Country),
                                             Genres = a.Genres[0].Name,
                                             ThumbUri = a.Thumb100Uri,
                                             Id = a.Id
                                         });
                                }
                                else
                                {
                                    App.ViewModel.TopArtists.Add(new ArtistModel()
                                         {
                                             Name = a.Name,
                                             Country = CountryCodes.CountryNameFromTwoLetter(a.Country),
                                             Genres = a.Genres[0].Name,
                                             ThumbUri = new Uri("/Assets/thumb_100_placeholder.png",
                                                                UriKind.Relative),
                                             Id = a.Id
                                         });
                                }
                            }
                        }
                        if (response != null && response.Error != null) 
                        {
                            ShowNokiaMusicApiError();
                        }
                        HideProgressIndicator("GetTopArtists()");
                    });
                });
                ShowProgressIndicator("GetTopArtists()");
            }
            ...
        }
    }


    Nokia Music Launchers:
    The next method from MusicApi Music Explorer shows how easy it is to launch Nokia Music to play the artist’s mix. The service can be opened on the page of a work or artist using the Nokia Music API. Some launcher methods in the Nokia Music API require unique artist, mix, or piece IDs. IDs can be obtained in response to requests from other Nokia Music Api services.

    using Nokia.Music.Phone;
    using Nokia.Music.Phone.Tasks;
    ...
    namespace MusicExplorer
    {
        ...
        public class MusicApi
        {
            ...
            public void LaunchArtistMix(string artistName)
            {
                ...
                PlayMixTask task = new PlayMixTask();
                task.ArtistName = artistName;
                task.Show();
            }
            ...
        }
    }


    Local music as a starting point: The
    list of performers in the Favorites is created using the LoadData MainViewModel method. The comments in the code describe the steps taken to create the list.

    using Microsoft.Xna.Framework.Media;
    ...
    namespace MusicExplorer.Models
    {
        ...
        public class MainViewModel : INotifyPropertyChanged
        {
            ...
            public ObservableCollection LocalAudio { get; private set; }
            ...
            MediaLibrary mediaLib = null; // Для доступа к локальным исполнителям и песням.
            ...
            public MainViewModel()
            {
                LocalAudio = new ObservableCollection();
                ...
                // Вставляет место для заголовка
                LocalAudio.Add(new ArtistModel() {
                    Name = "MusicExplorerTitlePlaceholder",
                    ItemHeight = "110",
                    ItemWidth = "400"
                });
            }
            ...
            public void LoadData()
            {
                mediaLib = new MediaLibrary();
                ...
                foreach (Artist a in mediaLib.Artists)
                {
                    if (a.Songs.Count <= 0) continue; // Пропускает исполнителя без композиций
                    string artist = a.Name;
                    int trackCount = a.Songs.Count;
                    int playCount = 0;
                    // Проверяет количество прослушиваний композиций исполнителя
                    foreach (Song s in a.Songs)
                    {
                        playCount += s.PlayCount;
                    }
                    // Вставляет исполнителя перед менее прослушиваемым.
                    bool artistAdded = false;
                    for (int i = 1; i < LocalAudio.Count; i++) // Index 0 зарезервирован для титульной записи
                    {
                        if (Convert.ToInt16(LocalAudio[i].PlayCount) < playCount)
                        {
                            this.LocalAudio.Insert(i, new ArtistModel()
                            {
                                Name = artist,
                                LocalTrackCount = Convert.ToString(trackCount),
                                PlayCount = Convert.ToString(playCount)
                            });
                            artistAdded = true;
                            break;
                        }
                    }
                    // ...Или вставляет исполнителя в конец списка, если он имеет меньшее количество прослушиваний.
                    if (artistAdded == false)
                    {
                        this.LocalAudio.Add(new ArtistModel()
                        {
                            Name = artist,
                            LocalTrackCount = Convert.ToString(trackCount),
                            PlayCount = Convert.ToString(playCount)
                        });
                    }
                    ...
                }
                // Продолжает, используя только топ-20 избранных исполнителей
                int removeIndex = App.ViewModel.LocalAudio.Count - 1;
                while (removeIndex > 20)
                {
                    App.ViewModel.LocalAudio.RemoveAt(removeIndex);
                    removeIndex--;
                }
                // Разделяет исполнителей на две категории «по размеру»
                foreach (ArtistModel m in App.ViewModel.LocalAudio)
                {
                    if (m.Name == "MusicExplorerTitlePlaceholder") continue;
                    if (Convert.ToInt16(m.LocalTrackCount) > (totalTrackCount / totalArtistCount))
                    {
                        m.ItemHeight = "200";
                        m.ItemWidth = "206";
                    }
                    else
                    {
                        m.ItemHeight = "100";
                        m.ItemWidth = "206";
                    }
                }
                ...
            }
            ...
        }
    }
    


    After creating a list of favorite artists, the database is searched using the Nokia Music API to create a list of “similar” ones for each of them. Then this list is built in accordance with the number of listeners of performers who built a list of similar ones. In addition, artists with songs stored on the device are excluded from the list, since the main idea is to promote new music.

    In the next article, we will look at working with the Advanced photo capturing API.

    Also popular now: