首页 > 解决方案 > 使用 Rodio crate 找不到文件

问题描述

我试图以字符串的形式从用户那里获取输入,并将其作为 Rodio 播放音频文件的路径传递。当我将硬编码路径传递给它时,它似乎工作得很好,但是当我输入与输入相同的路径时,它会给我一个错误。

代码:

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 {

    }
}

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

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

在这种情况下,两个输入都不起作用并给出此错误:

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

但是,当我对完全相同的输入进行硬编码时,它工作得很好。非常感谢您的帮助!

标签: rustrodio

解决方案


当您从标准输入读取一行时,它通常会在末尾包含新行(从您按下回车键开始)。

如果您使用调试格式说明符打印出字符串,即 println!("{:?}", &path);,它将显示字符串中您无法看到的任何转义序列。

您可能需要使用 str::trim 或类似方法来删除换行符。——科马克·奥布莱恩


推荐阅读