-
Notifications
You must be signed in to change notification settings - Fork 1
/
jquery-music-preview.js
111 lines (83 loc) · 2.5 KB
/
jquery-music-preview.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
* Author: Yves Van Broekhoven
* Created at: 2012-02-01
* Version: 1.0.0
* API docs: http://developer.echonest.com/
* jPlayer docs: http://jplayer.org/
*
* @example
* $.musicPreview('lady gaga', 'born this way');
*
*/
(function($){
var api_key = 'QNR9YFKVAPUN3PGLL'
, url = 'http://developer.echonest.com/api/v4/song/search?api_key={{api_key}}&format=json&results=1&artist={{artist}}&title={{title}}&bucket=id:7digital-US&bucket=audio_summary&bucket=tracks'
, response = {}
;
var _onSuccess
;
$.musicPreview = function(artist, title){
var dfd = $.Deferred();
// Error: artist required
if (artist === undefined || artist == '') {
return dfd.reject(response.artist_required);
}
// Error: song title required
if (title === undefined || title == '') {
return dfd.reject(response.title_required);
}
// Echonest request
var api_url = url.replace('{{api_key}}', api_key)
.replace('{{artist}}', artist)
.replace('{{title}}', title);
var jxhr = $.getJSON(api_url);
// Success: Echnonest request
jxhr.success(function(data){
_onSuccess.call(dfd, data);
});
// Error: Echnonest request
jxhr.error(function(data){
dfd.reject($.extend({}, response.request_error, { data: data }));
});
return dfd.promise();
};
_onSuccess = function(data){
// Error: No songs found
if (data.response.songs.length <= 0) {
return this.reject(response.no_songs_found);
}
// Error: No preview found
if (data.response.songs[0].tracks === undefined || data.response.songs[0].tracks.length <= 0) {
return this.reject(response.no_preview_found);
}
// Success: preview found
var preview_url = data.response.songs[0].tracks[0].preview_url;
return this.resolve($.extend({}, response.success, { preview_url: preview_url }));
};
response = {
artist_required: {
status: 'error'
, message: 'Artist required'
},
title_required: {
status: 'error'
, message: 'Song title required'
},
requeset_error: {
status: 'error'
, message: 'Can not connect to Echonest API'
},
no_songs_found: {
status: 'error'
, message: 'No soungs found'
},
no_preview_found: {
status: 'error'
, message: 'No preview found'
},
success: {
status: 'success'
, message: 'Preview found'
}
};
}(jQuery));