Debian Codegraph @

third_party/rust/midir/examples/test_reuse.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::{MidiInput, MidiOutput, Ignore};
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 mut input = String::new();
19
20 let mut midi_in = MidiInput::new("My Test Input")?;
21 midi_in.ignore(Ignore::None);
22 let mut midi_out = MidiOutput::new("My Test Output")?;
23
24 println!("Available input ports:");
25 let midi_in_ports = midi_in.ports();
26 for (i, p) in midi_in_ports.iter().enumerate() {
27 println!("{}: {}", i, midi_in.port_name(p)?);
28 }
29 print!("Please select input port: ");
30 stdout().flush()?;
31 stdin().read_line(&mut input)?;
32 let in_port = midi_in_ports.get(input.trim().parse::<usize>()?)
33 .ok_or("Invalid port number")?;
34
35 println!("\nAvailable output ports:");
36 let midi_out_ports = midi_out.ports();
37 for (i, p) in midi_out_ports.iter().enumerate() {
38 println!("{}: {}", i, midi_out.port_name(p)?);
39 }
40 print!("Please select output port: ");
41 stdout().flush()?;
42 input.clear();
43 stdin().read_line(&mut input)?;
44 let out_port = midi_out_ports.get(input.trim().parse::<usize>()?)
45 .ok_or("Invalid port number")?;
46
47 // This shows how to reuse input and output objects:
48 // Open/close the connections twice using the same MidiInput/MidiOutput objects
49 for _ in 0..2 {
50 println!("\nOpening connections");
51 let log_all_bytes = Vec::new(); // We use this as an example custom data to pass into the callback
52 let conn_in = midi_in.connect(in_port, "midir-test", |stamp, message, log| {
53 // The last of the three callback parameters is the object that we pass in as last parameter of `connect`.
54 println!("{}: {:?} (len = {})", stamp, message, message.len());
55 log.extend_from_slice(message);
56 }, log_all_bytes)?;
57
58 // One could get the log back here out of the error
59 let mut conn_out = midi_out.connect(out_port, "midir-test")?;
60
61 println!("Connections open, enter `q` to exit ...");
62
63 loop {
64 input.clear();
65 stdin().read_line(&mut input)?;
66 if input.trim() == "q" {
67 break;
68 } else {
69 conn_out.send(&[144, 60, 1])?;
70 sleep(Duration::from_millis(200));
71 conn_out.send(&[144, 60, 0])?;
72 }
73 }
74 println!("Closing connections");
75 let (midi_in_, log_all_bytes) = conn_in.close();
76 midi_in = midi_in_;
77 midi_out = conn_out.close();
78 println!("Connections closed");
79 println!("Received bytes: {:?}", log_all_bytes);
80 }
81 Ok(())
82 }