Skip to content

Instantly share code, notes, and snippets.

@ianhoffman
Last active February 16, 2021 22:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ianhoffman/618b81ff4a8b403ef7f7a605e6aa2cd8 to your computer and use it in GitHub Desktop.
Save ianhoffman/618b81ff4a8b403ef7f7a605e6aa2cd8 to your computer and use it in GitHub Desktop.
Example of a frontend API client
// var songInfo = {
// songName: ''
// lyric: '',
// }
//
// A pseudo-genre is the artist and their related artists.
//
function getArtist(searchString) {
// Make API call to get the artist from the search string
return $.ajax({
url: "https://api.musixmatch.com/ws/1.1/artist.search?format=jsonp&callback=callback&q_artist="
+ searchString
+ "&apikey=a19ef67c6dd8fda0c5be73eb1bab3e38"
}).success(function (data) {
// We have data about the artist
return data.message.body.artist_list[0].artist.artist_id;
});
}
function getSong(artistId) {
return $.ajax({
url: "https://api.musixmatch.com/ws/1.1/track.search?format=jsonp&callback=callback"
+ "&f_artist_id=" + artistId
+ "&f_has_lyrics=y&s_artist_rating=desc&s_track_rating=desc&quorum_factor=1&page_size=100&apikey=a19ef67c6dd8fda0c5be73eb1bab3e38"
}).success(function (data) {
return chooseSong(data.message.body.track_list);
});
}
function chooseSong(trackList) {
return trackList[Math.floor(Math.random() * trackList.length)].track.track_id;
}
function getLyrics(songId) {
return $.ajax({
url: "https://api.musixmatch.com/ws/1.1/track.lyrics.get?format=jsonp&callback=callback&track_id="
+ songId
+ "&apikey=a19ef67c6dd8fda0c5be73eb1bab3e38"
}).success(function (data) {
var lyricsText = data.message.body.lyrics.lyrics_body;
var lines = lyricsText.split("\n");
var randomLineNum = Math.floor(Math.random() * lines.length);
return lines[randomLineNum];
});
}
function getInfoForSearchTerm(searchTerm) {
return getArtist(searchTerm).success(function (artistId) {
return getSong(artistId).success(function (songName) {
return getLyrics(songName).success(function (lyric) {
return {
songName: songName,
lyric: lyric
}
});
});
});
}
function sayLyric(lyric) {
var msg = new SpeechSynthesisUtterance(lyric);
window.speechSynthesis.speak(msg);
}
$("#userRow").on("click", "#userButton", function(event) {
event.preventDefault();
// createArtistGenre();
getInfoForSearchTerm($(event.currentTarget).val().trim())
.success(function (songInfo) {
sayLyric(songInfo.lyric);
// Do other stuff with the song name
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment