Music

Struct Music 

Source
pub struct Music<'src> { /* private fields */ }
Expand description

Streamed music played from an audio file.

Musics are sounds that are streamed rather than completely loaded in memory.

This is especially useful for compressed musics that usually take hundreds of MB when they are uncompressed: by streaming it instead of loading it entirely, you avoid saturating the memory and have almost no loading delay. This implies that the underlying resource (file, stream or memory buffer) must remain valid for the lifetime of the Music object.

Apart from that, a Music has almost the same features as the SoundBuffer / Sound pair: you can play/pause/stop it, request its parameters (channels, sample rate), change the way it is played (pitch, volume, 3D position, …), etc.

As a sound stream, a music is played in its own thread in order not to block the rest of the program. This means that you can leave the music alone after calling play, it will manage itself very well.

Implementations§

Source§

impl<'src> Music<'src>

Creating and opening

Source

pub fn new() -> SfResult<Self>

Create a new (empty) Music.

Source

pub fn from_file(filename: &str) -> SfResult<Self>

Create a new Music by opening a music file

See Self::open_from_file.

Examples found in repository?
examples/sound.rs (line 38)
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}
More examples
Hide additional examples
examples/positional-audio.rs (line 59)
46fn main() -> Result<(), Box<dyn Error>> {
47    example_ensure_right_working_dir();
48
49    let mut rw = RenderWindow::new(
50        (800, 600),
51        "Positional audio demo",
52        Style::CLOSE,
53        &Default::default(),
54    )?;
55    rw.set_vertical_sync_enabled(true);
56    let font = Font::from_file("sansation.ttf")?;
57    let mut text = Text::new("", &font, 20);
58    let mut music = match std::env::args().nth(1) {
59        Some(music_path) => Music::from_file(&music_path)?,
60        None => Music::from_file("canary.wav")?,
61    };
62    if music.channel_count() != 1 {
63        return Err("Sorry, only sounds with 1 channel are supported.".into());
64    };
65    music.set_looping(true);
66    music.play();
67    music.set_position(Vector3::new(0., 0., 0.));
68
69    let mut listener_pos = Vector3::new(0.0, 0.0, 0.0);
70    let center = Vector2::new(400., 300.);
71    let [mut go_left, mut go_right, mut go_up, mut go_down] = [false; 4];
72    let clock = Clock::start()?;
73
74    while rw.is_open() {
75        while let Some(ev) = rw.poll_event() {
76            match ev {
77                Event::Closed => rw.close(),
78                Event::KeyPressed { code, .. } => match code {
79                    Key::A => go_left = true,
80                    Key::D => go_right = true,
81                    Key::W => go_up = true,
82                    Key::S => go_down = true,
83                    _ => {}
84                },
85                Event::KeyReleased { code, .. } => match code {
86                    Key::A => go_left = false,
87                    Key::D => go_right = false,
88                    Key::W => go_up = false,
89                    Key::S => go_down = false,
90                    _ => {}
91                },
92                _ => {}
93            }
94        }
95        let Vector2f { x: mx, y: my } = rw.mouse_position().as_other();
96        let speed = 0.05;
97        if go_left {
98            listener_pos.x -= speed;
99        }
100        if go_right {
101            listener_pos.x += speed;
102        }
103        if go_up {
104            listener_pos.y -= speed;
105        }
106        if go_down {
107            listener_pos.y += speed;
108        }
109        let scale = 20.0; // Scale the positions for better visualization
110        listener::set_position(listener_pos);
111        listener::set_direction(Vector3::new(
112            (mx - center.x) / scale,
113            (my - center.y) / scale,
114            -1.,
115        ));
116        let Vector3 {
117            x: lx,
118            y: ly,
119            z: lz,
120        } = listener::position();
121        let Vector3 {
122            x: dx,
123            y: dy,
124            z: dz,
125        } = listener::direction();
126        rw.clear(Color::BLACK);
127        let mut circle_shape = CircleShape::new(8.0, 32);
128        // Draw circle at center, representing position of music being played
129        circle_shape.set_position(center);
130        circle_shape.set_fill_color(Color::YELLOW);
131        let t = clock.elapsed_time().as_seconds();
132        let radius = 12.0 + t.sin() * 3.0;
133        circle_shape.set_radius(radius);
134        circle_shape.set_origin(radius);
135        rw.draw(&circle_shape);
136        // Draw circle representing listener
137        circle_shape.set_position((center.x + lx * scale, center.y + ly * scale));
138        circle_shape.set_origin(4.0);
139        circle_shape.set_radius(4.0);
140        circle_shape.set_fill_color(Color::GREEN);
141        rw.draw(&circle_shape);
142        // Draw line from listener to direction vector position
143        rw.draw_line(
144            circle_shape.position(),
145            (center.x + dx * scale, center.y + dy * scale).into(),
146            2.0,
147        );
148        text.set_string("WASD + mouse for movement of listener");
149        text.set_position(0.);
150        rw.draw(&text);
151        text.set_string(&format!("Listener position: {lx}, {ly}, {lz}"));
152        text.set_position((0., 20.0));
153        rw.draw(&text);
154        text.set_string(&format!("Listener direction: {dx}, {dy}, {dz}"));
155        text.set_position((0., 40.0));
156        rw.draw(&text);
157        rw.display();
158    }
159    Ok(())
160}
Source

pub fn from_stream<T: Read + Seek>( stream: &'src mut InputStream<'_, T>, ) -> SfResult<Self>

Create a new Music by “opening” it from a stream

See Self::open_from_stream.

Examples found in repository?
examples/music-stream.rs (line 16)
11fn main() -> Result<(), Box<dyn Error>> {
12    example_ensure_right_working_dir();
13
14    let mut file = File::open("orchestral.ogg")?;
15    let mut stream = InputStream::new(&mut file);
16    let mut music = Music::from_stream(&mut stream)?;
17
18    // Display Music informations
19    println!("orchestral.ogg :");
20    println!(" {} seconds", music.duration().as_seconds());
21    println!(" {} samples / sec", music.sample_rate());
22    println!(" {} channels", music.channel_count());
23
24    music.play();
25
26    while music.status() == SoundStatus::PLAYING {
27        // Leave some CPU time for other processes
28        sleep(Time::milliseconds(100));
29        // Display the playing position
30        print!(
31            "\rPlaying... {:.2} sec",
32            music.playing_offset().as_seconds()
33        );
34        let _ = std::io::stdout().flush();
35    }
36    println!();
37    Ok(())
38}
Source

pub fn from_memory(data: &'src [u8]) -> SfResult<Self>

Create a new Music by “opening” it from music data in memory

See Self::open_from_memory.

Source

pub fn open_from_file(&mut self, filename: &str) -> SfResult<()>

Open a new file for playback

This function doesn’t start playing the music (call play to do so). Here is a complete list of all the supported audio formats: ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam, w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.

§Arguments
  • filename - Path of the music file to open
Source

pub fn open_from_stream<T: Read + Seek>( &mut self, stream: &'src mut InputStream<'_, T>, ) -> SfResult<()>

Open music from a stream (a struct implementing Read and Seek)

This function doesn’t start playing the music (call play to do so). Here is a complete list of all the supported audio formats: ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam, w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.

§Arguments
  • stream - Your struct, implementing Read and Seek
Source

pub fn open_from_memory(&mut self, data: &'src [u8]) -> SfResult<()>

Create a new music and open it from memory

This function doesn’t start playing the music (call play to do so). Here is a complete list of all the supported audio formats: ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam, w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.

§Arguments
  • data - Slice of music data in memory
Source§

impl Music<'_>

Playback

Source

pub fn play(&mut self)

Start or resume playing a music

This function starts the music if it was stopped, resumes it if it was paused, and restarts it from beginning if it was it already playing. This function uses its own thread so that it doesn’t block the rest of the program while the music is played.

Examples found in repository?
examples/sound.rs (line 46)
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}
More examples
Hide additional examples
examples/music-stream.rs (line 24)
11fn main() -> Result<(), Box<dyn Error>> {
12    example_ensure_right_working_dir();
13
14    let mut file = File::open("orchestral.ogg")?;
15    let mut stream = InputStream::new(&mut file);
16    let mut music = Music::from_stream(&mut stream)?;
17
18    // Display Music informations
19    println!("orchestral.ogg :");
20    println!(" {} seconds", music.duration().as_seconds());
21    println!(" {} samples / sec", music.sample_rate());
22    println!(" {} channels", music.channel_count());
23
24    music.play();
25
26    while music.status() == SoundStatus::PLAYING {
27        // Leave some CPU time for other processes
28        sleep(Time::milliseconds(100));
29        // Display the playing position
30        print!(
31            "\rPlaying... {:.2} sec",
32            music.playing_offset().as_seconds()
33        );
34        let _ = std::io::stdout().flush();
35    }
36    println!();
37    Ok(())
38}
examples/positional-audio.rs (line 66)
46fn main() -> Result<(), Box<dyn Error>> {
47    example_ensure_right_working_dir();
48
49    let mut rw = RenderWindow::new(
50        (800, 600),
51        "Positional audio demo",
52        Style::CLOSE,
53        &Default::default(),
54    )?;
55    rw.set_vertical_sync_enabled(true);
56    let font = Font::from_file("sansation.ttf")?;
57    let mut text = Text::new("", &font, 20);
58    let mut music = match std::env::args().nth(1) {
59        Some(music_path) => Music::from_file(&music_path)?,
60        None => Music::from_file("canary.wav")?,
61    };
62    if music.channel_count() != 1 {
63        return Err("Sorry, only sounds with 1 channel are supported.".into());
64    };
65    music.set_looping(true);
66    music.play();
67    music.set_position(Vector3::new(0., 0., 0.));
68
69    let mut listener_pos = Vector3::new(0.0, 0.0, 0.0);
70    let center = Vector2::new(400., 300.);
71    let [mut go_left, mut go_right, mut go_up, mut go_down] = [false; 4];
72    let clock = Clock::start()?;
73
74    while rw.is_open() {
75        while let Some(ev) = rw.poll_event() {
76            match ev {
77                Event::Closed => rw.close(),
78                Event::KeyPressed { code, .. } => match code {
79                    Key::A => go_left = true,
80                    Key::D => go_right = true,
81                    Key::W => go_up = true,
82                    Key::S => go_down = true,
83                    _ => {}
84                },
85                Event::KeyReleased { code, .. } => match code {
86                    Key::A => go_left = false,
87                    Key::D => go_right = false,
88                    Key::W => go_up = false,
89                    Key::S => go_down = false,
90                    _ => {}
91                },
92                _ => {}
93            }
94        }
95        let Vector2f { x: mx, y: my } = rw.mouse_position().as_other();
96        let speed = 0.05;
97        if go_left {
98            listener_pos.x -= speed;
99        }
100        if go_right {
101            listener_pos.x += speed;
102        }
103        if go_up {
104            listener_pos.y -= speed;
105        }
106        if go_down {
107            listener_pos.y += speed;
108        }
109        let scale = 20.0; // Scale the positions for better visualization
110        listener::set_position(listener_pos);
111        listener::set_direction(Vector3::new(
112            (mx - center.x) / scale,
113            (my - center.y) / scale,
114            -1.,
115        ));
116        let Vector3 {
117            x: lx,
118            y: ly,
119            z: lz,
120        } = listener::position();
121        let Vector3 {
122            x: dx,
123            y: dy,
124            z: dz,
125        } = listener::direction();
126        rw.clear(Color::BLACK);
127        let mut circle_shape = CircleShape::new(8.0, 32);
128        // Draw circle at center, representing position of music being played
129        circle_shape.set_position(center);
130        circle_shape.set_fill_color(Color::YELLOW);
131        let t = clock.elapsed_time().as_seconds();
132        let radius = 12.0 + t.sin() * 3.0;
133        circle_shape.set_radius(radius);
134        circle_shape.set_origin(radius);
135        rw.draw(&circle_shape);
136        // Draw circle representing listener
137        circle_shape.set_position((center.x + lx * scale, center.y + ly * scale));
138        circle_shape.set_origin(4.0);
139        circle_shape.set_radius(4.0);
140        circle_shape.set_fill_color(Color::GREEN);
141        rw.draw(&circle_shape);
142        // Draw line from listener to direction vector position
143        rw.draw_line(
144            circle_shape.position(),
145            (center.x + dx * scale, center.y + dy * scale).into(),
146            2.0,
147        );
148        text.set_string("WASD + mouse for movement of listener");
149        text.set_position(0.);
150        rw.draw(&text);
151        text.set_string(&format!("Listener position: {lx}, {ly}, {lz}"));
152        text.set_position((0., 20.0));
153        rw.draw(&text);
154        text.set_string(&format!("Listener direction: {dx}, {dy}, {dz}"));
155        text.set_position((0., 40.0));
156        rw.draw(&text);
157        rw.display();
158    }
159    Ok(())
160}
Source

pub fn pause(&mut self)

Pause a music

This function pauses the music if it was playing, otherwise (music already paused or stopped) it has no effect.

Source

pub fn stop(&mut self)

Stop playing a music

This function stops the music if it was playing or paused, and does nothing if it was already stopped. It also resets the playing position (unlike pause).

Source§

impl Music<'_>

Query properties

Source

pub fn is_looping(&self) -> bool

Tell whether or not a music is in loop mode

Return true if the music is looping, false otherwise

Source

pub fn duration(&self) -> Time

Get the total duration of a music

Return Music duration

Examples found in repository?
examples/sound.rs (line 42)
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}
More examples
Hide additional examples
examples/music-stream.rs (line 20)
11fn main() -> Result<(), Box<dyn Error>> {
12    example_ensure_right_working_dir();
13
14    let mut file = File::open("orchestral.ogg")?;
15    let mut stream = InputStream::new(&mut file);
16    let mut music = Music::from_stream(&mut stream)?;
17
18    // Display Music informations
19    println!("orchestral.ogg :");
20    println!(" {} seconds", music.duration().as_seconds());
21    println!(" {} samples / sec", music.sample_rate());
22    println!(" {} channels", music.channel_count());
23
24    music.play();
25
26    while music.status() == SoundStatus::PLAYING {
27        // Leave some CPU time for other processes
28        sleep(Time::milliseconds(100));
29        // Display the playing position
30        print!(
31            "\rPlaying... {:.2} sec",
32            music.playing_offset().as_seconds()
33        );
34        let _ = std::io::stdout().flush();
35    }
36    println!();
37    Ok(())
38}
Source

pub fn channel_count(&self) -> u32

Return the number of channels of a music

1 channel means a mono sound, 2 means stereo, etc.

Return the number of channels

Examples found in repository?
examples/sound.rs (line 44)
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}
More examples
Hide additional examples
examples/music-stream.rs (line 22)
11fn main() -> Result<(), Box<dyn Error>> {
12    example_ensure_right_working_dir();
13
14    let mut file = File::open("orchestral.ogg")?;
15    let mut stream = InputStream::new(&mut file);
16    let mut music = Music::from_stream(&mut stream)?;
17
18    // Display Music informations
19    println!("orchestral.ogg :");
20    println!(" {} seconds", music.duration().as_seconds());
21    println!(" {} samples / sec", music.sample_rate());
22    println!(" {} channels", music.channel_count());
23
24    music.play();
25
26    while music.status() == SoundStatus::PLAYING {
27        // Leave some CPU time for other processes
28        sleep(Time::milliseconds(100));
29        // Display the playing position
30        print!(
31            "\rPlaying... {:.2} sec",
32            music.playing_offset().as_seconds()
33        );
34        let _ = std::io::stdout().flush();
35    }
36    println!();
37    Ok(())
38}
examples/positional-audio.rs (line 62)
46fn main() -> Result<(), Box<dyn Error>> {
47    example_ensure_right_working_dir();
48
49    let mut rw = RenderWindow::new(
50        (800, 600),
51        "Positional audio demo",
52        Style::CLOSE,
53        &Default::default(),
54    )?;
55    rw.set_vertical_sync_enabled(true);
56    let font = Font::from_file("sansation.ttf")?;
57    let mut text = Text::new("", &font, 20);
58    let mut music = match std::env::args().nth(1) {
59        Some(music_path) => Music::from_file(&music_path)?,
60        None => Music::from_file("canary.wav")?,
61    };
62    if music.channel_count() != 1 {
63        return Err("Sorry, only sounds with 1 channel are supported.".into());
64    };
65    music.set_looping(true);
66    music.play();
67    music.set_position(Vector3::new(0., 0., 0.));
68
69    let mut listener_pos = Vector3::new(0.0, 0.0, 0.0);
70    let center = Vector2::new(400., 300.);
71    let [mut go_left, mut go_right, mut go_up, mut go_down] = [false; 4];
72    let clock = Clock::start()?;
73
74    while rw.is_open() {
75        while let Some(ev) = rw.poll_event() {
76            match ev {
77                Event::Closed => rw.close(),
78                Event::KeyPressed { code, .. } => match code {
79                    Key::A => go_left = true,
80                    Key::D => go_right = true,
81                    Key::W => go_up = true,
82                    Key::S => go_down = true,
83                    _ => {}
84                },
85                Event::KeyReleased { code, .. } => match code {
86                    Key::A => go_left = false,
87                    Key::D => go_right = false,
88                    Key::W => go_up = false,
89                    Key::S => go_down = false,
90                    _ => {}
91                },
92                _ => {}
93            }
94        }
95        let Vector2f { x: mx, y: my } = rw.mouse_position().as_other();
96        let speed = 0.05;
97        if go_left {
98            listener_pos.x -= speed;
99        }
100        if go_right {
101            listener_pos.x += speed;
102        }
103        if go_up {
104            listener_pos.y -= speed;
105        }
106        if go_down {
107            listener_pos.y += speed;
108        }
109        let scale = 20.0; // Scale the positions for better visualization
110        listener::set_position(listener_pos);
111        listener::set_direction(Vector3::new(
112            (mx - center.x) / scale,
113            (my - center.y) / scale,
114            -1.,
115        ));
116        let Vector3 {
117            x: lx,
118            y: ly,
119            z: lz,
120        } = listener::position();
121        let Vector3 {
122            x: dx,
123            y: dy,
124            z: dz,
125        } = listener::direction();
126        rw.clear(Color::BLACK);
127        let mut circle_shape = CircleShape::new(8.0, 32);
128        // Draw circle at center, representing position of music being played
129        circle_shape.set_position(center);
130        circle_shape.set_fill_color(Color::YELLOW);
131        let t = clock.elapsed_time().as_seconds();
132        let radius = 12.0 + t.sin() * 3.0;
133        circle_shape.set_radius(radius);
134        circle_shape.set_origin(radius);
135        rw.draw(&circle_shape);
136        // Draw circle representing listener
137        circle_shape.set_position((center.x + lx * scale, center.y + ly * scale));
138        circle_shape.set_origin(4.0);
139        circle_shape.set_radius(4.0);
140        circle_shape.set_fill_color(Color::GREEN);
141        rw.draw(&circle_shape);
142        // Draw line from listener to direction vector position
143        rw.draw_line(
144            circle_shape.position(),
145            (center.x + dx * scale, center.y + dy * scale).into(),
146            2.0,
147        );
148        text.set_string("WASD + mouse for movement of listener");
149        text.set_position(0.);
150        rw.draw(&text);
151        text.set_string(&format!("Listener position: {lx}, {ly}, {lz}"));
152        text.set_position((0., 20.0));
153        rw.draw(&text);
154        text.set_string(&format!("Listener direction: {dx}, {dy}, {dz}"));
155        text.set_position((0., 40.0));
156        rw.draw(&text);
157        rw.display();
158    }
159    Ok(())
160}
Source

pub fn sample_rate(&self) -> u32

Get the sample rate of a music

The sample rate is the number of audio samples played per second. The higher, the better the quality.

Return the sample rate, in number of samples per second

Examples found in repository?
examples/sound.rs (line 43)
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}
More examples
Hide additional examples
examples/music-stream.rs (line 21)
11fn main() -> Result<(), Box<dyn Error>> {
12    example_ensure_right_working_dir();
13
14    let mut file = File::open("orchestral.ogg")?;
15    let mut stream = InputStream::new(&mut file);
16    let mut music = Music::from_stream(&mut stream)?;
17
18    // Display Music informations
19    println!("orchestral.ogg :");
20    println!(" {} seconds", music.duration().as_seconds());
21    println!(" {} samples / sec", music.sample_rate());
22    println!(" {} channels", music.channel_count());
23
24    music.play();
25
26    while music.status() == SoundStatus::PLAYING {
27        // Leave some CPU time for other processes
28        sleep(Time::milliseconds(100));
29        // Display the playing position
30        print!(
31            "\rPlaying... {:.2} sec",
32            music.playing_offset().as_seconds()
33        );
34        let _ = std::io::stdout().flush();
35    }
36    println!();
37    Ok(())
38}
Source

pub fn status(&self) -> SoundStatus

Get the current status of a music (stopped, paused, playing)

Return current status

Examples found in repository?
examples/sound.rs (line 48)
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}
More examples
Hide additional examples
examples/music-stream.rs (line 26)
11fn main() -> Result<(), Box<dyn Error>> {
12    example_ensure_right_working_dir();
13
14    let mut file = File::open("orchestral.ogg")?;
15    let mut stream = InputStream::new(&mut file);
16    let mut music = Music::from_stream(&mut stream)?;
17
18    // Display Music informations
19    println!("orchestral.ogg :");
20    println!(" {} seconds", music.duration().as_seconds());
21    println!(" {} samples / sec", music.sample_rate());
22    println!(" {} channels", music.channel_count());
23
24    music.play();
25
26    while music.status() == SoundStatus::PLAYING {
27        // Leave some CPU time for other processes
28        sleep(Time::milliseconds(100));
29        // Display the playing position
30        print!(
31            "\rPlaying... {:.2} sec",
32            music.playing_offset().as_seconds()
33        );
34        let _ = std::io::stdout().flush();
35    }
36    println!();
37    Ok(())
38}
Source

pub fn playing_offset(&self) -> Time

Get the current playing position of a music

Return the current playing position

Examples found in repository?
examples/sound.rs (line 50)
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}
More examples
Hide additional examples
examples/music-stream.rs (line 32)
11fn main() -> Result<(), Box<dyn Error>> {
12    example_ensure_right_working_dir();
13
14    let mut file = File::open("orchestral.ogg")?;
15    let mut stream = InputStream::new(&mut file);
16    let mut music = Music::from_stream(&mut stream)?;
17
18    // Display Music informations
19    println!("orchestral.ogg :");
20    println!(" {} seconds", music.duration().as_seconds());
21    println!(" {} samples / sec", music.sample_rate());
22    println!(" {} channels", music.channel_count());
23
24    music.play();
25
26    while music.status() == SoundStatus::PLAYING {
27        // Leave some CPU time for other processes
28        sleep(Time::milliseconds(100));
29        // Display the playing position
30        print!(
31            "\rPlaying... {:.2} sec",
32            music.playing_offset().as_seconds()
33        );
34        let _ = std::io::stdout().flush();
35    }
36    println!();
37    Ok(())
38}
Source

pub fn loop_points(&self) -> TimeSpan

Get the positions of the of the music’s looping sequence.

§Warning

Since set_loop_points performs some adjustments on the provided values and rounds them to internal samples, a call to loop_points is not guaranteed to return the same times passed into a previous call to set_loop_points. However, it is guaranteed to return times that will map to the valid internal samples of this Music if they are later passed to set_loop_points.

Source§

impl Music<'_>

Set properties

Source

pub fn set_looping(&mut self, looping: bool)

Sets whether this music should loop or not.

If true, the music will restart from beginning after reaching the end and so on, until it is stopped or set_looping(false) is called.

By default, the music will not loop.

Examples found in repository?
examples/positional-audio.rs (line 65)
46fn main() -> Result<(), Box<dyn Error>> {
47    example_ensure_right_working_dir();
48
49    let mut rw = RenderWindow::new(
50        (800, 600),
51        "Positional audio demo",
52        Style::CLOSE,
53        &Default::default(),
54    )?;
55    rw.set_vertical_sync_enabled(true);
56    let font = Font::from_file("sansation.ttf")?;
57    let mut text = Text::new("", &font, 20);
58    let mut music = match std::env::args().nth(1) {
59        Some(music_path) => Music::from_file(&music_path)?,
60        None => Music::from_file("canary.wav")?,
61    };
62    if music.channel_count() != 1 {
63        return Err("Sorry, only sounds with 1 channel are supported.".into());
64    };
65    music.set_looping(true);
66    music.play();
67    music.set_position(Vector3::new(0., 0., 0.));
68
69    let mut listener_pos = Vector3::new(0.0, 0.0, 0.0);
70    let center = Vector2::new(400., 300.);
71    let [mut go_left, mut go_right, mut go_up, mut go_down] = [false; 4];
72    let clock = Clock::start()?;
73
74    while rw.is_open() {
75        while let Some(ev) = rw.poll_event() {
76            match ev {
77                Event::Closed => rw.close(),
78                Event::KeyPressed { code, .. } => match code {
79                    Key::A => go_left = true,
80                    Key::D => go_right = true,
81                    Key::W => go_up = true,
82                    Key::S => go_down = true,
83                    _ => {}
84                },
85                Event::KeyReleased { code, .. } => match code {
86                    Key::A => go_left = false,
87                    Key::D => go_right = false,
88                    Key::W => go_up = false,
89                    Key::S => go_down = false,
90                    _ => {}
91                },
92                _ => {}
93            }
94        }
95        let Vector2f { x: mx, y: my } = rw.mouse_position().as_other();
96        let speed = 0.05;
97        if go_left {
98            listener_pos.x -= speed;
99        }
100        if go_right {
101            listener_pos.x += speed;
102        }
103        if go_up {
104            listener_pos.y -= speed;
105        }
106        if go_down {
107            listener_pos.y += speed;
108        }
109        let scale = 20.0; // Scale the positions for better visualization
110        listener::set_position(listener_pos);
111        listener::set_direction(Vector3::new(
112            (mx - center.x) / scale,
113            (my - center.y) / scale,
114            -1.,
115        ));
116        let Vector3 {
117            x: lx,
118            y: ly,
119            z: lz,
120        } = listener::position();
121        let Vector3 {
122            x: dx,
123            y: dy,
124            z: dz,
125        } = listener::direction();
126        rw.clear(Color::BLACK);
127        let mut circle_shape = CircleShape::new(8.0, 32);
128        // Draw circle at center, representing position of music being played
129        circle_shape.set_position(center);
130        circle_shape.set_fill_color(Color::YELLOW);
131        let t = clock.elapsed_time().as_seconds();
132        let radius = 12.0 + t.sin() * 3.0;
133        circle_shape.set_radius(radius);
134        circle_shape.set_origin(radius);
135        rw.draw(&circle_shape);
136        // Draw circle representing listener
137        circle_shape.set_position((center.x + lx * scale, center.y + ly * scale));
138        circle_shape.set_origin(4.0);
139        circle_shape.set_radius(4.0);
140        circle_shape.set_fill_color(Color::GREEN);
141        rw.draw(&circle_shape);
142        // Draw line from listener to direction vector position
143        rw.draw_line(
144            circle_shape.position(),
145            (center.x + dx * scale, center.y + dy * scale).into(),
146            2.0,
147        );
148        text.set_string("WASD + mouse for movement of listener");
149        text.set_position(0.);
150        rw.draw(&text);
151        text.set_string(&format!("Listener position: {lx}, {ly}, {lz}"));
152        text.set_position((0., 20.0));
153        rw.draw(&text);
154        text.set_string(&format!("Listener direction: {dx}, {dy}, {dz}"));
155        text.set_position((0., 40.0));
156        rw.draw(&text);
157        rw.display();
158    }
159    Ok(())
160}
Source

pub fn set_playing_offset(&mut self, time_offset: Time)

Change the current playing position of a music

The playing position can be changed when the music is either paused or playing.

§Arguments
  • timeOffset - New playing position
Source

pub fn set_loop_points(&mut self, time_points: TimeSpan)

Sets the beginning and end of the music’s looping sequence.

Loop points allow one to specify a pair of positions such that, when the music is enabled for looping, it will seamlessly seek to the beginning whenever it encounters the end. Valid ranges for timePoints.offset and timePoints.length are [0, Dur) and (0, Dur-offset] respectively, where Dur is the value returned by duration. Note that the EOF “loop point” from the end to the beginning of the stream is still honored, in case the caller seeks to a point after the end of the loop range. This function can be safely called at any point after a stream is opened, and will be applied to a playing sound without affecting the current playing offset.

Trait Implementations§

Source§

impl<'src> Debug for Music<'src>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for Music<'_>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl SoundSource for Music<'_>

Source§

fn set_pitch(&mut self, pitch: f32)

Set the pitch of the sound. Read more
Source§

fn set_volume(&mut self, volume: f32)

Set the volume of the sound. Read more
Source§

fn set_position<P: Into<Vector3f>>(&mut self, position: P)

Set the 3D position of the sound in the audio scene. Read more
Source§

fn set_relative_to_listener(&mut self, relative: bool)

Make the sound’s position relative to the listener or absolute. Read more
Source§

fn set_min_distance(&mut self, distance: f32)

Set the minimum distance of the sound. Read more
Source§

fn set_attenuation(&mut self, attenuation: f32)

Set the attenuation factor of the sound. Read more
Source§

fn pitch(&self) -> f32

Get the pitch of the sound.
Source§

fn volume(&self) -> f32

Get the volume of the sound. Read more
Source§

fn position(&self) -> Vector3f

Get the 3D position of the sound in the audio scene.
Source§

fn is_relative_to_listener(&self) -> bool

Tell whether the sound’s position is relative to the listener or is absolute.
Source§

fn min_distance(&self) -> f32

Get the minimum distance of the sound.
Source§

fn attenuation(&self) -> f32

Get the attenuation factor of the sound.
Source§

impl Send for Music<'_>

Source§

impl Sync for Music<'_>

Auto Trait Implementations§

§

impl<'src> Freeze for Music<'src>

§

impl<'src> RefUnwindSafe for Music<'src>

§

impl<'src> Unpin for Music<'src>

§

impl<'src> !UnwindSafe for Music<'src>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.