Quelques exemples AppleScript de composition musicale aléatoire.
Jouer les sons à l’aide de iTunes
-- Nombre de sons joués
set nombre to 8
-- Librairie des sons
property sounds_folder : "/System/Library/Sounds/"
-- Demander le chemin complet au bon format
set dossier to POSIX file sounds_folder
-- Lister les fichiers de ce dossier
tell application "Finder" to set my_sounds to name of items of folder dossier
set nb_max to count of my_sounds
set path_sound to ""
if (nb_max > 0) then
repeat with ii from 1 to nombre
-- choisir au son au hasard
set this_sound to (random number from 1 to nb_max)
-- recopier le nom du fichier
set my_sound to item this_sound of my_sounds
-- Donner le chemin
set my_sound to (dossier & my_sound as text)
-- Jouer le son via iTunes
tell application "iTunes" to play my_sound
-- Boucle
end repeat
end ifTellement rapide que l’on entend que le dernier son.
Jouer les sons à l’aide de afplay
afplay (Audio File Play) est une commande livrée avec Mac OS X.
-- Nombre de sons joués
set nombre to 8
-- Librairie des sons
property sounds_folder : "/System/Library/Sounds/"
-- Demander le chemin complet au bon format
set dossier to POSIX file sounds_folder
-- Lister les fichiers de ce dossier
tell application "Finder" to set my_sounds to name of items of folder dossier
set nb_max to count of my_sounds
set path_sound to ""
if (nb_max > 0) then
repeat with ii from 1 to nombre
-- choisir au son au hasard
set this_sound to (random number from 1 to nb_max)
-- recopier le nom du fichier
set my_sound to item this_sound of my_sounds
-- Donner le chemin POSIX
set my_sound to (sounds_folder & my_sound as text)
-- Jouer le son via afplay
do shell script "afplay " & my_sound
-- Boucle
end repeat
end ifVariante : mettre l’ensemble dans une chaine et n’appeler le terminal qu’une fois. Gain de temps entre les morceaux :
set nombre to 8
property sounds_folder : "/System/Library/Sounds/"
-- Demander le chemin complet au bon format
set dossier to POSIX file sounds_folder
tell application "Finder" to set my_sounds to name of items of folder dossier
set nb_max to count of my_sounds
set path_sound to ""
if (nb_max > 0) then
repeat while (nombre ≥ 0)
set this_sound to (random number from 1 to nb_max)
set my_sound to item this_sound of my_sounds
set path_sound to path_sound & "afplay -t 1 " & sounds_folder & my_sound & "; "
set nombre to nombre - 1
end repeat
end if
--log path_sound
do shell script path_soundafplay propose quelques options. Pour les connaitre, ne lisez pas le man qui est incomplet, mais plutôt afplay -h.
L’option -t permet de règler le temps d’exécution. Par exemple :
set boucle to 8
repeat with ii from 1 to boucle
do shell script "afplay -t 2 /System/Library/Sounds/Purr.aiff; afplay -t 0.5 /System/Library/Sounds/Purr.aiff;afplay -t 0.5 /System/Library/Sounds/Purr.aiff;"
end repeat