sound/
sound.rs

1use {
2    sfml::{
3        SfResult,
4        audio::{Music, Sound, SoundBuffer, SoundStatus},
5        system::{Time, sleep},
6    },
7    std::io::Write,
8};
9
10include!("../example_common.rs");
11
12// Play a Sound
13fn play_sound() -> SfResult<()> {
14    let buffer = SoundBuffer::from_file("canary.wav")?;
15
16    // Display sound informations
17    println!("canary.wav :");
18    println!(" {} seconds", buffer.duration().as_seconds());
19    println!(" {} samples / sec", buffer.sample_rate());
20    println!(" {} channels", buffer.channel_count());
21
22    let mut sound = Sound::with_buffer(&buffer);
23    sound.play();
24
25    while sound.status() == SoundStatus::PLAYING {
26        // Display the playing position
27        print!("\rPlaying... {:.2}", sound.playing_offset().as_seconds());
28        let _ = std::io::stdout().flush();
29        // Leave some CPU time for other processes
30        sleep(Time::milliseconds(100));
31    }
32    println!();
33    Ok(())
34}
35
36// Play a Music
37fn play_music() -> SfResult<()> {
38    let mut music = Music::from_file("orchestral.ogg")?;
39
40    // Display Music informations
41    println!("orchestral.ogg :");
42    println!(" {} seconds", music.duration().as_seconds());
43    println!(" {} samples / sec", music.sample_rate());
44    println!(" {} channels", music.channel_count());
45
46    music.play();
47
48    while music.status() == SoundStatus::PLAYING {
49        // Display the playing position
50        print!("\rPlaying... {:.2}", music.playing_offset().as_seconds());
51        let _ = std::io::stdout().flush();
52        // Leave some CPU time for other processes
53        sleep(Time::milliseconds(100));
54    }
55
56    println!();
57    Ok(())
58}
59
60fn main() -> SfResult<()> {
61    example_ensure_right_working_dir();
62
63    play_sound()?;
64    play_music()?;
65    Ok(())
66}