Debian Codegraph @

mido/scripts/mido_play.py

raw symbols SCIP
1 #!/usr/bin/env python3
2
3 # SPDX-FileCopyrightText: 2013 Ole Martin Bjorndalen <[email protected]>
4 #
5 # SPDX-License-Identifier: MIT
6
7 """
8 Play MIDI file on output port.
9
10 Example:
11
12 mido-play some_file.mid
13
14 Todo:
15
16 - add option for printing messages
17 """
18 import argparse
19 import sys
20
21 import mido
22 from mido import Message, MidiFile, tempo2bpm
23
24
25 def parse_args():
26 parser = argparse.ArgumentParser(description=__doc__)
27 arg = parser.add_argument
28
29 arg('-o', '--output-port',
30 help='Mido port to send output to')
31
32 arg('-m', '--print-messages',
33 dest='print_messages',
34 action='store_true',
35 default=False,
36 help='Print messages as they are played back')
37
38 arg('-q', '--quiet',
39 dest='quiet',
40 action='store_true',
41 default=False,
42 help='print nothing')
43
44 arg('files',
45 metavar='FILE',
46 nargs='+',
47 help='MIDI file to play')
48
49 return parser.parse_args()
50
51
52 def play_file(output, filename, print_messages):
53 midi_file = MidiFile(filename)
54
55 print(f'Playing {midi_file.filename}.')
56 length = midi_file.length
57 print('Song length: {} minutes, {} seconds.'.format(
58 int(length / 60),
59 int(length % 60)))
60 print('Tracks:')
61 for i, track in enumerate(midi_file.tracks):
62 print(f' {i:2d}: {track.name.strip()!r}')
63
64 for message in midi_file.play(meta_messages=True):
65 if print_messages:
66 sys.stdout.write(repr(message) + '\n')
67 sys.stdout.flush()
68
69 if isinstance(message, Message):
70 output.send(message)
71 elif message.type == 'set_tempo':
72 print('Tempo changed to {:.1f} BPM.'.format(
73 tempo2bpm(message.tempo)))
74
75 print()
76
77
78 def main():
79 args = parse_args()
80
81 if args.quiet:
82 global print
83 def print(*args):
84 pass
85
86 try:
87 with mido.open_output(args.output_port) as output:
88 print(f'Using output {output.name!r}.')
89 output.reset()
90 try:
91 for filename in args.files:
92 play_file(output, filename, args.print_messages)
93 finally:
94 print()
95 output.reset()
96 except KeyboardInterrupt:
97 pass
98
99
100 if __name__ == '__main__':
101 main()