| 1 |
extern crate midir; |
| 2 |
|
| 3 |
use std::io::{stdin, stdout, Write}; |
| 4 |
use std::error::Error; |
| 5 |
|
| 6 |
use midir::{MidiInput, MidiOutput, MidiIO, Ignore}; |
| 7 |
|
| 8 |
fn main() { |
| 9 |
match run() { |
| 10 |
Ok(_) => (), |
| 11 |
Err(err) => println!("Error: {}", err) |
| 12 |
} |
| 13 |
} |
| 14 |
|
| 15 |
#[cfg(not(target_arch = "wasm32"))] // conn_out is not `Send` in Web MIDI, which means it cannot be passed to connect |
| 16 |
fn run() -> Result<(), Box<dyn Error>> { |
| 17 |
let mut midi_in = MidiInput::new("midir forwarding input")?; |
| 18 |
midi_in.ignore(Ignore::None); |
| 19 |
let midi_out = MidiOutput::new("midir forwarding output")?; |
| 20 |
|
| 21 |
let in_port = select_port(&midi_in, "input")?; |
| 22 |
println!(); |
| 23 |
let out_port = select_port(&midi_out, "output")?; |
| 24 |
|
| 25 |
println!("\nOpening connections"); |
| 26 |
let in_port_name = midi_in.port_name(&in_port)?; |
| 27 |
let out_port_name = midi_out.port_name(&out_port)?; |
| 28 |
|
| 29 |
let mut conn_out = midi_out.connect(&out_port, "midir-forward")?; |
| 30 |
|
| 31 |
// _conn_in needs to be a named parameter, because it needs to be kept alive until the end of the scope |
| 32 |
let _conn_in = midi_in.connect(&in_port, "midir-forward", move |stamp, message, _| { |
| 33 |
conn_out.send(message).unwrap_or_else(|_| println!("Error when forwarding message ...")); |
| 34 |
println!("{}: {:?} (len = {})", stamp, message, message.len()); |
| 35 |
}, ())?; |
| 36 |
|
| 37 |
println!("Connections open, forwarding from '{}' to '{}' (press enter to exit) ...", in_port_name, out_port_name); |
| 38 |
|
| 39 |
let mut input = String::new(); |
| 40 |
stdin().read_line(&mut input)?; // wait for next enter key press |
| 41 |
|
| 42 |
println!("Closing connections"); |
| 43 |
Ok(()) |
| 44 |
} |
| 45 |
|
| 46 |
fn select_port<T: MidiIO>(midi_io: &T, descr: &str) -> Result<T::Port, Box<dyn Error>> { |
| 47 |
println!("Available {} ports:", descr); |
| 48 |
let midi_ports = midi_io.ports(); |
| 49 |
for (i, p) in midi_ports.iter().enumerate() { |
| 50 |
println!("{}: {}", i, midi_io.port_name(p)?); |
| 51 |
} |
| 52 |
print!("Please select {} port: ", descr); |
| 53 |
stdout().flush()?; |
| 54 |
let mut input = String::new(); |
| 55 |
stdin().read_line(&mut input)?; |
| 56 |
let port = midi_ports.get(input.trim().parse::<usize>()?) |
| 57 |
.ok_or("Invalid port number")?; |
| 58 |
Ok(port.clone()) |
| 59 |
} |
| 60 |
|
| 61 |
#[cfg(target_arch = "wasm32")] |
| 62 |
fn run() -> Result<(), Box<dyn Error>> { |
| 63 |
println!("test_forward cannot run on Web MIDI"); |
| 64 |
Ok(()) |
| 65 |
} |