| 1 |
extern crate midir; |
| 2 |
|
| 3 |
use std::io::{stdin, stdout, Write}; |
| 4 |
use std::error::Error; |
| 5 |
|
| 6 |
use midir::{MidiInput, Ignore}; |
| 7 |
|
| 8 |
fn main() { |
| 9 |
match run() { |
| 10 |
Ok(_) => (), |
| 11 |
Err(err) => println!("Error: {}", err) |
| 12 |
} |
| 13 |
} |
| 14 |
|
| 15 |
fn run() -> Result<(), Box<dyn Error>> { |
| 16 |
let mut input = String::new(); |
| 17 |
|
| 18 |
let mut midi_in = MidiInput::new("midir reading input")?; |
| 19 |
midi_in.ignore(Ignore::None); |
| 20 |
|
| 21 |
// Get an input port (read from console if multiple are available) |
| 22 |
let in_ports = midi_in.ports(); |
| 23 |
let in_port = match in_ports.len() { |
| 24 |
0 => return Err("no input port found".into()), |
| 25 |
1 => { |
| 26 |
println!("Choosing the only available input port: {}", midi_in.port_name(&in_ports[0]).unwrap()); |
| 27 |
&in_ports[0] |
| 28 |
}, |
| 29 |
_ => { |
| 30 |
println!("\nAvailable input ports:"); |
| 31 |
for (i, p) in in_ports.iter().enumerate() { |
| 32 |
println!("{}: {}", i, midi_in.port_name(p).unwrap()); |
| 33 |
} |
| 34 |
print!("Please select input port: "); |
| 35 |
stdout().flush()?; |
| 36 |
let mut input = String::new(); |
| 37 |
stdin().read_line(&mut input)?; |
| 38 |
in_ports.get(input.trim().parse::<usize>()?) |
| 39 |
.ok_or("invalid input port selected")? |
| 40 |
} |
| 41 |
}; |
| 42 |
|
| 43 |
println!("\nOpening connection"); |
| 44 |
let in_port_name = midi_in.port_name(in_port)?; |
| 45 |
|
| 46 |
// _conn_in needs to be a named parameter, because it needs to be kept alive until the end of the scope |
| 47 |
let _conn_in = midi_in.connect(in_port, "midir-read-input", move |stamp, message, _| { |
| 48 |
println!("{}: {:?} (len = {})", stamp, message, message.len()); |
| 49 |
}, ())?; |
| 50 |
|
| 51 |
println!("Connection open, reading input from '{}' (press enter to exit) ...", in_port_name); |
| 52 |
|
| 53 |
input.clear(); |
| 54 |
stdin().read_line(&mut input)?; // wait for next enter key press |
| 55 |
|
| 56 |
println!("Closing connection"); |
| 57 |
Ok(()) |
| 58 |
} |