Debian Codegraph @

third_party/rust/midir/examples/test_play.rs

raw
1 extern crate midir;
2
3 use std::thread::sleep;
4 use std::time::Duration;
5 use std::io::{stdin, stdout, Write};
6 use std::error::Error;
7
8 use midir::{MidiOutput, MidiOutputPort};
9
10 fn main() {
11 match run() {
12 Ok(_) => (),
13 Err(err) => println!("Error: {}", err)
14 }
15 }
16
17 fn run() -> Result<(), Box<dyn Error>> {
18 let midi_out = MidiOutput::new("My Test Output")?;
19
20 // Get an output port (read from console if multiple are available)
21 let out_ports = midi_out.ports();
22 let out_port: &MidiOutputPort = match out_ports.len() {
23 0 => return Err("no output port found".into()),
24 1 => {
25 println!("Choosing the only available output port: {}", midi_out.port_name(&out_ports[0]).unwrap());
26 &out_ports[0]
27 },
28 _ => {
29 println!("\nAvailable output ports:");
30 for (i, p) in out_ports.iter().enumerate() {
31 println!("{}: {}", i, midi_out.port_name(p).unwrap());
32 }
33 print!("Please select output port: ");
34 stdout().flush()?;
35 let mut input = String::new();
36 stdin().read_line(&mut input)?;
37 out_ports.get(input.trim().parse::<usize>()?)
38 .ok_or("invalid output port selected")?
39 }
40 };
41
42 println!("\nOpening connection");
43 let mut conn_out = midi_out.connect(out_port, "midir-test")?;
44 println!("Connection open. Listen!");
45 {
46 // Define a new scope in which the closure `play_note` borrows conn_out, so it can be called easily
47 let mut play_note = |note: u8, duration: u64| {
48 const NOTE_ON_MSG: u8 = 0x90;
49 const NOTE_OFF_MSG: u8 = 0x80;
50 const VELOCITY: u8 = 0x64;
51 // We're ignoring errors in here
52 let _ = conn_out.send(&[NOTE_ON_MSG, note, VELOCITY]);
53 sleep(Duration::from_millis(duration * 150));
54 let _ = conn_out.send(&[NOTE_OFF_MSG, note, VELOCITY]);
55 };
56
57 sleep(Duration::from_millis(4 * 150));
58
59 play_note(66, 4);
60 play_note(65, 3);
61 play_note(63, 1);
62 play_note(61, 6);
63 play_note(59, 2);
64 play_note(58, 4);
65 play_note(56, 4);
66 play_note(54, 4);
67 }
68 sleep(Duration::from_millis(150));
69 println!("\nClosing connection");
70 // This is optional, the connection would automatically be closed as soon as it goes out of scope
71 conn_out.close();
72 println!("Connection closed");
73 Ok(())
74 }