Created
February 25, 2018 12:18
-
-
Save Sinkler/d75f524169c59ff4164044c2af3c765e to your computer and use it in GitHub Desktop.
iTunes Apple Script - Create a shuffled playlist from another one
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
'use strict'; | |
function toLower(s) { | |
return s.toLowerCase(); | |
} | |
function makeArray(length) { | |
return Array.from(new Array(length), (x,i) => i); | |
} | |
function shuffleArray(a) { | |
for (let i = a.length - 1; i > 0; i--) { | |
const j = Math.floor(Math.random() * (i + 1)); | |
[a[i], a[j]] = [a[j], a[i]]; | |
} | |
return a; | |
} | |
function playListByName(name, create) { | |
var app = Application('iTunes'), | |
index = app.playlists.name().map(toLower).indexOf(toLower(name)); | |
if (index === -1) { | |
if (create) { | |
console.log('Create the "' + name + '" playlist'); | |
var playlist = app.UserPlaylist().make(); | |
playlist.name = name; | |
return playlist; | |
} | |
console.log('The "' + name + '" playlist is not found'); | |
return; | |
} else { | |
return app.playlists.at(index); | |
} | |
} | |
function clearPlayList(playlist) { | |
console.log('Clear the "' + playlist.name() + '" playlist'); | |
const length = playlist.tracks.length; | |
for (let i = 0; i < length; i++) { | |
playlist.tracks[0].delete(); | |
} | |
} | |
function shufflePlaylist(from_playlist, to_playlist, count) { | |
if (!from_playlist) return; | |
if (!to_playlist) return; | |
var app = Application('iTunes'), | |
length = from_playlist.tracks.length, | |
shuffle = shuffleArray(makeArray(length)).slice(0, count); | |
clearPlayList(to_playlist); | |
console.log('Add songs to the "' + to_playlist.name() + '" playlist'); | |
for (let i in shuffle) { | |
from_playlist.tracks[shuffle[i]].duplicate({to: to_playlist}); | |
} | |
console.log('Play'); | |
app.songRepeat = 'off'; | |
app.shuffleEnabled = false; | |
app.play(to_playlist); | |
console.log('Ready'); | |
} | |
shufflePlaylist(playListByName('Random'), | |
playListByName('Random Shuffle', true), | |
100); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment