This repository has been archived by the owner on Sep 21, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
audio_analysis.html
332 lines (298 loc) · 16.2 KB
/
audio_analysis.html
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
<html>
<head>
<title>Spotify API Call</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<link rel="stylesheet" href="https://minicss.org/flavorFiles/mini-default.css">
</head>
<body>
<h1>Type the name of a track you love and its artist!</h1>
<h3>For optimal results, please be case-sensitive with your searches.</h3>
<form onsubmit="runJavaScript()" id="myForm">
<label for="track">Track name:</label>
<input type="text" name="trackName" id="track">
<br>
<label for="artist">Artist name:</label>
<input type="text" name="artistName" id="artist">
<input type="submit">
</form>
<script src="spotify.js"></script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://d3js.org/d3.v4.js"></script>
<div id="my_dataviz"></div>
<script type='text/JavaScript'>
function runJavaScript() {
$.ajax(
{
method: "POST",
url: "https://accounts.spotify.com/api/token",
data: {
"grant_type":"client_credentials",
// "code": code,
// "redirect_uri": myurl,
"client_secret":"6902861723d7473eb55d9dd341c575da",
"client_id":"d30523ae4669444eb8812a8979bfb04c",
},
success: function(result) {
console.log(result.access_token);
var access_token = result.access_token;
// handle result...
var params = (new URL(document.location)).searchParams;
if (params.has('artistName') && params.has('trackName')) {
var artistName = params.get('artistName');
console.log(artistName);
var trackName = params.get('trackName');
console.log(trackName);
var spotifyApi = new SpotifyWebApi();
spotifyApi.setAccessToken(access_token);
spotifyApi.searchTracks(trackName).then(
function(data) {
console.log(data);
for (var i = 0; i < 100; i++) {
var resultArtist = data.tracks.items[i].artists[0].name;
if (resultArtist == artistName) {
console.log(resultArtist);
var trackId = data.tracks.items[i].id;
console.log(trackId);
spotifyApi.getAudioAnalysisForTrack(trackId).then(
function(data) {
console.log(data);
var loudness = [];
var brightness = [];
var flatness = [];
var strength = [];
var segments = data.segments;
var segments_length = segments.length;
console.log(segments_length);
for (var i = 0; i < segments_length; i++) {
var timbre_segment = data.segments[i].timbre[0];
loudness.push(timbre_segment);
}
for (var i = 0; i < segments_length; i++) {
var timbre_segment = data.segments[i].timbre[1];
brightness.push(timbre_segment);
}
for (var i = 0; i < segments_length; i++) {
var timbre_segment = data.segments[i].timbre[2];
flatness.push(timbre_segment);
}
for (var i = 0; i < segments_length; i++) {
var timbre_segment = data.segments[i].timbre[3];
strength.push(timbre_segment);
}
console.log(loudness);
console.log(brightness);
console.log(flatness);
console.log(strength);
// setting dimensions & margins of the graph
var margin = {top: 20, right: 20, bottom: 60, left: 120},
width = 1200 - margin.left - margin.right,
height = 430 - margin.top - margin.bottom;
// append the svg (scalable vector graphics) to the body of the page
var svg = d3.select("#my_dataviz")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// list of titles of the 4 datasets
var keys = ['loudness', 'brightness', 'flatness', 'strength'];
// finding [min, max] of dataset for y-axis
var extenty = d3.extent(strength);
var ymin = extenty[0];
var ymax = extenty[1];
// add the x axis
var x = d3.scaleLinear()
.domain([0, segments_length])
// maybe (segments_length - 1)
// (function(d) {return d;}) gives data set
.range([0, width]);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x).ticks(5));
// add the y axis
var y = d3.scaleLinear()
.domain([ymin, ymax])
.range([height, 0]);
svg.append("g")
.call(d3.axisLeft(y));
// colors
var color = d3.scaleOrdinal()
.domain(keys)
.range(['#e41a1c','#377eb8','#4daf4a','#984ea3'])
// stack the data
var stackedData = d3.stack()
.offset(d3.stackOffsetSilhouette)
.keys(keys)
(data)
// show the areas
svg
.selectAll("mylayers")
.data(stackedData)
.enter()
.append("path")
.style("fill", function(d) {
// console.log(d[0].data)
// console.log(color(d.keys))
return color(d.keys); })
.attr("d", d3.area()
.x0(function(d) {
return x(i);
})
.x1(function(d, i) {
// console.log(d.data)
// console.log(i)
return x(i);
})
.y0(function(d) {
// return y(d.data);
return y(0);
})
.y1(function(d) {
return y(d.data);
})
)
})
break
}
}
}
);
}
}
},
);
}
/*
var authUrl = 'https://accounts.spotify.com/api/token';
//var grant_type = client_credentials;
var headerID = 'd30523ae4669444eb8812a8979bfb04c';
var headerSecret = '6902861723d7473eb55d9dd341c575da';
var encodedID = btoa(headerID);
var encodedSecret = btoa(headerSecret);
var encodedData = encodedID + ':' + encodedSecret;
var xyz = new XMLHttpRequest();
xyz.open("POST",authUrl,true);
xyz.setRequestHeader('Authorization','Basic' + encodedData);
xyz.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
}
}
console.log(xyz);
xyz.send('grant_type=client_credentials');
function queryArtistAndTrack() {
let params = (new URL(document.location)).searchParams;
if (params.has('artistName') && params.has('trackName')) {
let artistName = params.get('artistName');
console.log(artistName);
let trackName = params.get('trackName');
console.log(trackName);
let queryURL = "https://api.spotify.com/v1/search" + "?q=track:" + trackName + "%20artist:" + artistName + "&type=track";
console.log(queryURL);
httpGet(queryURL);
}
}
function httpGet(theURL, cbFunction) {
let xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', theURL);
xmlHttp.send();
xmlHttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cbFunction(this);
}
}
}
function convertToCSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
function exportCSVFile(headers, items, fileTitle) {
if (headers) {
items.unshift(headers);
}
// Convert Object to JSON
var jsonObject = JSON.stringify(items);
var csv = this.convertToCSV(jsonObject);
var exportedFilenmae = fileTitle + '.csv' || 'export.csv';
var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, exportedFilenmae);
} else {
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", exportedFilenmae);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
var headers = {
model: 'Phone Model'.replace(/,/g, ''), // remove commas to avoid errors
chargers: "Chargers",
cases: "Cases",
earphones: "Earphones"
};
itemsNotFormatted = [
{
model: 'Samsung S7',
chargers: '55',
cases: '56',
earphones: '57',
scratched: '2'
},
{
model: 'Pixel XL',
chargers: '77',
cases: '78',
earphones: '79',
scratched: '4'
},
{
model: 'iPhone 7',
chargers: '88',
cases: '89',
earphones: '90',
scratched: '6'
}
];
var itemsFormatted = [];
// format the data
itemsNotFormatted.forEach((item) => {
itemsFormatted.push({
model: item.model.replace(/,/g, ''), // remove commas to avoid errors,
chargers: item.chargers,
cases: item.cases,
earphones: item.earphones
});
});
var fileTitle = 'orders'; // or 'my-unique-title'
// call the exportCSVFile() function to process the JSON and trigger the download
exportCSVFile(headers, itemsFormatted, fileTitle);
*/
runJavaScript();
</script>
<p id="paragraph">This website reveals a visualization of the timbre of any song...</p>
<p id="paragraph"></p>
<p id="paragraph">Timbre can be defined as the character or quality of a musical sound or voice.</p>
<p id="paragraph">This visualization compares four characteristics of timbre:</p>
<p id="paragraph_blue">LOUDNESS</p>
<p id="paragraph_yellow">BRIGHTNESS</p>
<p id="paragraph_brown">FLATNESS</p>
<p id="paragraph_pink">STRENGTH OF ATTACK</p>
</body>
</html>