rustrodio

File not found using Rodio crate


I am trying to take input from the user in the form of a String and passing it as a path for Rodio to play the audio file. When I pass it a hard-coded path it seems to work just fine but when I type the same path in as input it will give me an error.

code:

fn main() {

    let mut path = String::new();
    io::stdin().read_line(&mut path); //to get input from the user

    player(&path);
}
fn player(path: &str){
    let (stream, stream_handle) = rodio::OutputStream::try_default().unwrap();

    // Load a sound from a file, using a path relative to Cargo.toml
    let file = File::open(path).unwrap();
    let source = rodio::Decoder::new(BufReader::new(file)).unwrap();
    stream_handle.play_raw(source.convert_samples());

    // The sound plays in a separate audio thread,
    // so we need to keep the main thread alive while it's playing.
    loop {

    }
}

Input: C:\Users\username\AppData\Roaming\Equinotify\songs\Olivia Rodrigo - good 4 u (Official Video).wav

Input: C:\\Users\\Drago\\AppData\\Roaming\\Equinotify\\songs\\Olivia Rodrigo - good 4 u (Official Video).wav

Neither input works in this scenario and gives this error:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 123, kind: Other, message: "The filename, directory name, or volume label syntax is incorrect." }', src\main.rs:24:33

However, when I hardcode the exact same input it works just fine. Your help is greatly appreciated!


Solution

  • When you read a line from stdin, it typically comes with the new line included at the end (from when you pressed the enter key).

    If you print out the strings using the debug format specifier, i.e. println!("{:?}", &path);, it will show any escape sequences in the string you could not otherwise see.

    You may need to use str::trim or a similar method to remove the newline. – Cormac O'Brien