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
impl<'src> Music<'src>
Creating and opening
Sourcepub fn from_file(filename: &str) -> SfResult<Self>
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?
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
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}Sourcepub fn from_stream<T: Read + Seek>(
stream: &'src mut InputStream<'_, T>,
) -> SfResult<Self>
pub fn from_stream<T: Read + Seek>( stream: &'src mut InputStream<'_, T>, ) -> SfResult<Self>
Create a new Music by “opening” it from a stream
Examples found in repository?
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}Sourcepub fn from_memory(data: &'src [u8]) -> SfResult<Self>
pub fn from_memory(data: &'src [u8]) -> SfResult<Self>
Create a new Music by “opening” it from music data in memory
Sourcepub fn open_from_file(&mut self, filename: &str) -> SfResult<()>
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
Sourcepub fn open_from_stream<T: Read + Seek>(
&mut self,
stream: &'src mut InputStream<'_, T>,
) -> SfResult<()>
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
Sourcepub fn open_from_memory(&mut self, data: &'src [u8]) -> SfResult<()>
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
impl Music<'_>
Playback
Sourcepub fn play(&mut self)
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?
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
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}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§impl Music<'_>
Query properties
impl Music<'_>
Query properties
Sourcepub fn is_looping(&self) -> bool
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
Sourcepub fn duration(&self) -> Time
pub fn duration(&self) -> Time
Get the total duration of a music
Return Music duration
Examples found in repository?
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
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}Sourcepub fn channel_count(&self) -> u32
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?
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
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}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}Sourcepub fn sample_rate(&self) -> u32
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?
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
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}Sourcepub fn status(&self) -> SoundStatus
pub fn status(&self) -> SoundStatus
Get the current status of a music (stopped, paused, playing)
Return current status
Examples found in repository?
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
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}Sourcepub fn playing_offset(&self) -> Time
pub fn playing_offset(&self) -> Time
Get the current playing position of a music
Return the current playing position
Examples found in repository?
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
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}Sourcepub fn loop_points(&self) -> TimeSpan
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
impl Music<'_>
Set properties
Sourcepub fn set_looping(&mut self, looping: bool)
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?
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}Sourcepub fn set_playing_offset(&mut self, time_offset: Time)
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
Sourcepub fn set_loop_points(&mut self, time_points: TimeSpan)
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.