aboutsummaryrefslogtreecommitdiff
path: root/ztunekey
blob: 61eb9e6d0623dce66fa0f43736e063ddd8bca3a7 (plain)
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
#!/bin/sh

# icon from:
# https://vectorified.com/images/guitar-tuner-icon-28.jpg
# ...installed via:
# convert guitar-tuner-icon-28.jpg .local/share/icons/hicolor/256x256/apps/ztunekey.png

if [ "$1" = "--help" ]; then
  cat <<EOF
ztunekey: show tuning and key of an audio file, using a zenity-based UI.

Usage: ztunekey [file]

[file] is an audio file, in any format supported by mplayer (since
mplayer is used to convert it to a .wav file for processing).

With no [file], ztunekey queries audacious (using audtool) to get the
currently playing file. This will fail if audacious isn't running.

The tuning (in cents relative to A440) and the detected key (and
relative key, e.g. G (Em) or A (F#m)) are shown in a window, after the
file is analyzed.
EOF
  exit 0
fi

ICON=ztunekey
ZOPT='--width 300 --height 100 --title Tuning/Key'
file="$1"

if [ "$file" = "" ]; then
  file="$( audtool --current-song-filename )"
  if [ "$file" = "" ]; then
    zenity --error $ZOPT --text="Audacious is not running, or no song is playing."
    exit 1
  fi
fi

if [ ! -e "$file" ]; then
  zenity --error $ZOPT --text="No such file:\\n$file"
  exit 1
fi

bn="$( basename "$file" )"
tmpfile=/tmp/ztunekey.$$.wav

keyfile=/tmp/key.$$
tunefile=/tmp/tuning.$$
( mplayer -really-quiet -benchmark -vo null -ao pcm:fast:file=$tmpfile "$file"
  find_tuning -q "$tmpfile" > $tunefile   &
  find_key    -q "$tmpfile" > $keyfile    &
  wait ) | zenity --progress --no-cancel $ZOPT --icon-name=ztunekey --text="$bn" --pulsate --auto-close

TUNING="$( cat $tunefile )"
KEY="$( cat $keyfile )"
rm -f $keyfile $tunefile

zenity --question $ZOPT --icon-name=ztunekey --text="$bn\\nTuning: $TUNING cents\\nKey: $KEY )\\n\\nRetune to standard?"
[ "$?" = 1 ] && exit 1

zenity --scale $ZOPT --icon-name=ztunekey --text="Semitones to transpose?\\n0 = original key."  --min-value=-12 --max-value=12 --value=0 > /tmp/semi.$$

S="$( cat /tmp/semi.$$ )"
rm -f /tmp/semi.$$
P="$( perl -MPOSIX=round -e "printf '%+2.2f', round(100 * ($S - $TUNING / 100)) / 100" )"
newfile="$( echo "$bn" | sed 's,\.[^.]*$,'$P'.wav,' )"

mkdir -p ~/retuned
cd ~/retuned
rubberband --pitch $P $tmpfile "$newfile" | zenity --progress --no-cancel $ZOPT --icon-name=ztunekey --text "Retuning $bn by $P semitones." --pulsate --auto-close
flacfile="$( basename "$newfile" .wav )".flac
flac -f --delete-input-file -o "$flacfile" "$newfile" | zenity --progress --no-cancel $ZOPT --icon-name=ztunekey --text "Encoding $flacfile" --pulsate --auto-close
id3cp "$file" "$flacfile"
id3 -2 -t "%|%t||%_f|? (Retuned $P)" "$flacfile"
audtool --playlist-addurl-to-new-playlist ~/retuned/"$flacfile"