Repository navigation
Expand file tree
/
Copy pathSong Sorting.html
More file actions
89 lines (74 loc) · 2.61 KB
/
Copy pathSong Sorting.html
File metadata and controls
89 lines (74 loc) · 2.61 KB
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
<!DOCTYPE html>
<html>
<head>
<title>Sort Songs by BPM</title>
</head>
<body>
<h1>Sort Songs by BPM</h1>
<input type="text" id="songLink" placeholder="Enter YouTube/Spotify URL">
<button onclick="addSong()">Add Song</button>
<button onclick="sortSongs()">Sort Songs</button>
<ul id="songList"></ul>
<script>
const songList = document.getElementById('songList');
let songs = [];
async function addSong() {
const url = document.getElementById('songLink').value.trim();
if (isValidUrl(url)) {
try {
const { title, artist, bpm } = await fetchSongInfo(url);
songs.push({ title, artist, bpm, url });
displaySongs();
} catch (error) {
console.error('Error fetching song info:', error);
alert('Error fetching song info. Please try again later.');
}
} else {
alert('Invalid URL. Please enter a valid YouTube or Spotify URL.');
}
}
function isValidUrl(input) {
const urlPattern = /^(https?:\/\/)?(www\.)?(youtube\.com|youtu\.?be|open\.spotify\.com)/;
return urlPattern.test(input);
}
async function fetchSongInfo(url) {
const youtubePattern = /(?:\/watch\?v=|youtu\.be\/)([\w-]{11})/;
const spotifyPattern = /(?:\/track\/|open\.spotify\.com\/track\/)([\w\d]+)/;
let title = null;
let artist = null;
let bpm = null;
const youtubeMatch = url.match(youtubePattern);
const spotifyMatch = url.match(spotifyPattern);
if (youtubeMatch) {
const videoId = youtubeMatch[1];
const response = await fetch(`https://www.googleapis.com/youtube/v3/videos?id=${videoId}&part=snippet&key=YOUR_YOUTUBE_API_KEY`);
const data = await response.json();
title = data.items[0]?.snippet.title;
artist = 'Unknown'; // YouTube doesn't provide artist info
} else if (spotifyMatch) {
const trackId = spotifyMatch[1];
const response = await fetch(`https://api.spotify.com/v1/tracks/${trackId}`);
const data = await response.json();
title = data.name;
artist = data.artists.map(artist => artist.name).join(', ');
}
return { title, artist, bpm };
}
function sortSongs() {
songs.sort((a, b) => a.bpm - b.bpm);
displaySongs();
}
function displaySongs() {
songList.innerHTML = '';
songs.forEach(song => {
const listItem = document.createElement('li');
const link = document.createElement('a');
link.href = song.url;
link.textContent = `${song.title ? `${song.title} - ` : ''}${song.artist ? `${song.artist} - ` : ''}${song.bpm ? `BPM: ${song.bpm}` : 'Unknown BPM'}`;
listItem.appendChild(link);
songList.appendChild(listItem);
});
}
</script>
</body>
</html>