pub struct Sound<'buf> { /* private fields */ }
Expand description
Regular sound that can be played in the audio environment.
Sound
is the type to use to play sounds.
It provides:
- Control (play, pause, stop)
- Ability to modify output parameters in real-time (pitch, volume, …)
- 3D spatial features (position, attenuation, …).
Sound
is perfect for playing short sounds that can fit in memory and require no latency,
like foot steps or gun shots. For longer sounds, like background musics or long speeches,
rather see Music
(which is based on streaming).
In order to work, a sound must be given a buffer of audio data to play.
Audio data (samples) is stored in SoundBuffer
, and attached to a sound with the
set_buffer
function. The buffer object attached to a sound must remain alive as long as
the sound uses it. Note that multiple sounds can use the same sound buffer at the same time.
Implementations§
Source§impl<'buf> Sound<'buf>
Creation
impl<'buf> Sound<'buf>
Creation
Sourcepub fn new() -> Self
pub fn new() -> Self
Examples found in repository?
65fn main() -> Result<(), Box<dyn Error>> {
66 example_ensure_right_working_dir();
67
68 assert!(
69 capture::is_available(),
70 "Sorry, audio capture is not supported by your system"
71 );
72 let default_device = capture::default_device();
73 let devices = capture::available_devices();
74 let mut rw = RenderWindow::new(
75 (800, 600),
76 "Custom sound recorder",
77 Style::CLOSE,
78 &Default::default(),
79 )?;
80 rw.set_vertical_sync_enabled(true);
81 let font = Font::from_file("sansation.ttf")?;
82 let (mut rec, recv) = MyRecorder::new();
83 let mut samp_buf = Vec::new();
84 let mut driver = SoundRecorderDriver::new(&mut rec);
85 let mut started = false;
86 let mut snd_buf = SoundBuffer::new()?;
87 let mut samp_accum = Vec::new();
88 let mut sound = Some(Sound::new());
89 let mut selected_dev_idx = 0;
90 let mut mode = Mode::Main;
91 let mut input_buf = String::new();
92 let mut desired_sample_rate = 44_100;
93 let mut desired_channel_count = 2;
94
95 while rw.is_open() {
96 while let Some(ev) = rw.poll_event() {
97 match ev {
98 Event::Closed => rw.close(),
99 Event::KeyPressed { code, .. } => match mode {
100 Mode::Main => match code {
101 Key::R => {
102 if started {
103 driver.stop();
104 sound = None;
105 snd_buf.load_from_samples(
106 &samp_accum[..],
107 desired_channel_count,
108 desired_sample_rate,
109 )?;
110 samp_accum.clear();
111 started = false;
112 } else {
113 driver.set_device(devices[selected_dev_idx].to_str()?)?;
114 driver.set_channel_count(desired_channel_count);
115 driver.start(desired_sample_rate)?;
116 started = true;
117 }
118 }
119 Key::P => {
120 if !started {
121 let sound = sound.insert(Sound::with_buffer(&snd_buf));
122 sound.play();
123 }
124 }
125 Key::D => mode = Mode::SetDevice,
126 Key::S => {
127 input_buf = desired_sample_rate.to_string();
128 mode = Mode::SetSampleRate;
129 }
130 Key::C => {
131 input_buf = desired_channel_count.to_string();
132 mode = Mode::SetChannelCount;
133 }
134 Key::E => {
135 input_buf = "export.wav".to_string();
136 mode = Mode::Export;
137 }
138 _ => {}
139 },
140 Mode::SetDevice => match code {
141 Key::Up => {
142 selected_dev_idx -= selected_dev_idx.saturating_sub(1);
143 }
144 Key::Down => {
145 if selected_dev_idx + 1 < devices.len() {
146 selected_dev_idx += 1;
147 }
148 }
149 Key::Enter | Key::Escape => {
150 mode = Mode::Main;
151 }
152 _ => {}
153 },
154 Mode::SetSampleRate => {
155 if code == Key::Enter {
156 desired_sample_rate = input_buf.parse()?;
157 mode = Mode::Main;
158 }
159 }
160 Mode::SetChannelCount => {
161 if code == Key::Enter {
162 desired_channel_count = input_buf.parse()?;
163 mode = Mode::Main;
164 }
165 }
166 Mode::Export => {
167 if code == Key::Enter {
168 snd_buf.save_to_file(&input_buf)?;
169 mode = Mode::Main;
170 }
171 }
172 },
173 Event::TextEntered { unicode } => match mode {
174 Mode::SetSampleRate | Mode::SetChannelCount => {
175 if unicode.is_ascii_digit() {
176 input_buf.push(unicode);
177 } else if unicode == 0x8 as char {
178 input_buf.pop();
179 }
180 }
181 Mode::Export => {
182 if !unicode.is_ascii_control() {
183 input_buf.push(unicode);
184 } else if unicode == 0x8 as char {
185 input_buf.pop();
186 }
187 }
188 Mode::Main | Mode::SetDevice => {}
189 },
190 _ => {}
191 }
192 }
193 if let Ok(samples) = recv.try_recv() {
194 samp_accum.extend_from_slice(&samples);
195 samp_buf = samples;
196 }
197 rw.clear(Color::rgb(10, 60, 40));
198 let mut writer = TextWriter::new(&font, 20, 0.0, 0.0);
199 macro_rules! w {
200 ($($arg:tt)*) => {
201 writer.write(&format!($($arg)*), &mut rw);
202 }
203 }
204 match mode {
205 Mode::Main => {
206 w!("D - set device, S - set sample rate, C - set channel count, E - export");
207 let s = if started {
208 "Press R to stop recording"
209 } else {
210 "Press R to start recording. Press P to play the recording."
211 };
212 w!("{s}");
213 w!(
214 "{} @ {} Hz\n{} samples, {} channels, {} bytes recorded",
215 driver.device(),
216 driver.sample_rate(),
217 samp_buf.len(),
218 driver.channel_count(),
219 samp_accum.len() * 2,
220 );
221 let mut rect = RectangleShape::new();
222 for (i, &sample) in samp_buf.iter().enumerate() {
223 let ratio = samp_buf.len() as f32 / rw.size().x as f32;
224 rect.set_position((i as f32 / ratio, 300.0));
225 rect.set_size((2.0, sample as f32 / 48.0));
226 rw.draw(&rect);
227 }
228 }
229 Mode::SetDevice => {
230 for (i, dev) in devices.iter().enumerate() {
231 let default_str = if dev == &*default_device {
232 " (default)"
233 } else {
234 ""
235 };
236 let color = if selected_dev_idx == i {
237 Color::YELLOW
238 } else {
239 Color::WHITE
240 };
241 writer.text.set_fill_color(color);
242 w!("{}: {}{default_str}", i + 1, dev.to_str()?);
243 }
244 }
245 Mode::SetSampleRate => {
246 w!("Enter desired sample rate");
247 w!("{input_buf}");
248 }
249 Mode::SetChannelCount => {
250 w!("Enter desired channel count");
251 w!("{input_buf}");
252 }
253 Mode::Export => {
254 w!("Enter filename to export as");
255 w!("{input_buf}");
256 }
257 }
258 rw.display();
259 }
260 Ok(())
261}
Sourcepub fn with_buffer(buffer: &'buf SoundBuffer) -> Self
pub fn with_buffer(buffer: &'buf SoundBuffer) -> Self
Create a new Sound
with a buffer
Examples found in repository?
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}
More examples
55fn main() -> SfResult<()> {
56 example_ensure_right_working_dir();
57
58 let mut tex_holder = ResourceHolder::<Texture, _>::default();
59 tex_holder.load("frank", "frank.jpeg")?;
60 let mut sb_holder = ResourceHolder::<SoundBuffer, _>::default();
61 sb_holder.load("canary", "canary.wav")?;
62 let mut rw = RenderWindow::new(
63 (800, 600),
64 "Resource holder test",
65 Style::CLOSE,
66 &Default::default(),
67 )?;
68 rw.set_vertical_sync_enabled(true);
69 let mut sound = Sound::with_buffer(sb_holder.get("canary"));
70 sound.play();
71 while rw.is_open() {
72 while let Some(ev) = rw.poll_event() {
73 match ev {
74 Event::Closed
75 | Event::KeyPressed {
76 code: Key::Escape, ..
77 } => rw.close(),
78 _ => {}
79 }
80 }
81 rw.clear(Color::BLACK);
82 rw.draw(&Sprite::with_texture(tex_holder.get("frank")));
83 rw.display();
84 }
85 Ok(())
86}
12fn main() -> Result<(), Box<dyn Error>> {
13 // Check that the device can capture audio
14 assert!(
15 capture::is_available(),
16 "Sorry, audio capture is not supported by your system"
17 );
18 let default_device = capture::default_device();
19 let devices = capture::available_devices();
20 println!("{} recording devices available:", devices.len());
21 for (i, device) in devices.iter().enumerate() {
22 let def_str = if device == &*default_device {
23 " (default)"
24 } else {
25 ""
26 };
27 println!("Device {i}: {device}{def_str}");
28 }
29
30 // Choose the sample rate
31 println!(
32 "Please input device and sample rate, then press enter\n\
33 Example:\n\
34 1 22050 # record at 22050 Hz on device 1\n\
35 Default (on empty input) is device 0 and 44100 Hz (CD quality)"
36 );
37 let stdin = std::io::stdin();
38 let mut reader = stdin.lock();
39 let mut line = String::new();
40 reader.read_line(&mut line)?;
41 let input = line.trim_end();
42 let mut tokens = input.split_whitespace();
43 let device_idx = if let Some(token) = tokens.next() {
44 match token.parse::<usize>() {
45 Ok(value) => value,
46 Err(e) => return Err(format!("Input is not valid: {e}").into()),
47 }
48 } else {
49 0
50 };
51 let sample_rate = if let Some(token) = tokens.next() {
52 match token.parse::<u32>() {
53 Ok(value) => value,
54 Err(e) => return Err(format!("Input is not valid: {e}").into()),
55 }
56 } else {
57 44_100
58 };
59
60 // Here we'll use an integrated custom recorder,
61 // which saves the captured data into a SoundBuffer
62 let mut recorder = SoundBufferRecorder::new();
63 match devices.get(device_idx) {
64 Some(device) => {
65 recorder.set_device(device.to_str()?)?;
66 }
67 None => {
68 eprintln!("No device with index {device_idx}");
69 }
70 }
71
72 // Audio capture is done in a separate thread,
73 // so we can block the main thread while it is capturing
74 recorder.start(sample_rate)?;
75 println!(
76 "Recording on device {} @ {} Hz...\nPress enter to stop",
77 recorder.device().to_str().unwrap_or("<invalid utf-8>"),
78 recorder.sample_rate()
79 );
80 reader.read_line(&mut String::new())?;
81 recorder.stop();
82
83 // Get the buffer containing the captured data
84 let buffer = recorder.buffer();
85
86 // Display captured sound information
87 println!("Sound information :");
88 println!(" {} seconds", buffer.duration().as_seconds());
89 println!(" {} samples / sec", buffer.sample_rate());
90 println!(" {} channels", buffer.channel_count());
91
92 // Choose what to do with the recorded sound data
93 print!("What do you want to do with captured sound (p = play, s = save) ? ");
94 let _ = std::io::stdout().flush();
95 let mut resp = String::new();
96 reader.read_line(&mut resp)?;
97
98 if resp.trim() == "s" {
99 // Choose a filename
100 println!("Choose the file to create: ");
101 let mut filename = String::new();
102 reader.read_line(&mut filename)?;
103
104 // Save the buffer
105 if buffer.save_to_file(filename.trim()).is_err() {
106 eprintln!("Error saving buffer to {}!", filename.trim());
107 }
108 } else {
109 let mut sound = Sound::with_buffer(buffer);
110
111 sound.play();
112
113 while sound.status() == SoundStatus::PLAYING {
114 // Display the playing position
115 print!(
116 "\rPlaying... {:.2} sec",
117 sound.playing_offset().as_seconds()
118 );
119 let _ = std::io::stdout().flush();
120 // Leave some CPU time for other processes
121 sleep(Time::milliseconds(100));
122 }
123 }
124
125 // Finished
126 println!("\nDone!");
127 Ok(())
128}
65fn main() -> Result<(), Box<dyn Error>> {
66 example_ensure_right_working_dir();
67
68 assert!(
69 capture::is_available(),
70 "Sorry, audio capture is not supported by your system"
71 );
72 let default_device = capture::default_device();
73 let devices = capture::available_devices();
74 let mut rw = RenderWindow::new(
75 (800, 600),
76 "Custom sound recorder",
77 Style::CLOSE,
78 &Default::default(),
79 )?;
80 rw.set_vertical_sync_enabled(true);
81 let font = Font::from_file("sansation.ttf")?;
82 let (mut rec, recv) = MyRecorder::new();
83 let mut samp_buf = Vec::new();
84 let mut driver = SoundRecorderDriver::new(&mut rec);
85 let mut started = false;
86 let mut snd_buf = SoundBuffer::new()?;
87 let mut samp_accum = Vec::new();
88 let mut sound = Some(Sound::new());
89 let mut selected_dev_idx = 0;
90 let mut mode = Mode::Main;
91 let mut input_buf = String::new();
92 let mut desired_sample_rate = 44_100;
93 let mut desired_channel_count = 2;
94
95 while rw.is_open() {
96 while let Some(ev) = rw.poll_event() {
97 match ev {
98 Event::Closed => rw.close(),
99 Event::KeyPressed { code, .. } => match mode {
100 Mode::Main => match code {
101 Key::R => {
102 if started {
103 driver.stop();
104 sound = None;
105 snd_buf.load_from_samples(
106 &samp_accum[..],
107 desired_channel_count,
108 desired_sample_rate,
109 )?;
110 samp_accum.clear();
111 started = false;
112 } else {
113 driver.set_device(devices[selected_dev_idx].to_str()?)?;
114 driver.set_channel_count(desired_channel_count);
115 driver.start(desired_sample_rate)?;
116 started = true;
117 }
118 }
119 Key::P => {
120 if !started {
121 let sound = sound.insert(Sound::with_buffer(&snd_buf));
122 sound.play();
123 }
124 }
125 Key::D => mode = Mode::SetDevice,
126 Key::S => {
127 input_buf = desired_sample_rate.to_string();
128 mode = Mode::SetSampleRate;
129 }
130 Key::C => {
131 input_buf = desired_channel_count.to_string();
132 mode = Mode::SetChannelCount;
133 }
134 Key::E => {
135 input_buf = "export.wav".to_string();
136 mode = Mode::Export;
137 }
138 _ => {}
139 },
140 Mode::SetDevice => match code {
141 Key::Up => {
142 selected_dev_idx -= selected_dev_idx.saturating_sub(1);
143 }
144 Key::Down => {
145 if selected_dev_idx + 1 < devices.len() {
146 selected_dev_idx += 1;
147 }
148 }
149 Key::Enter | Key::Escape => {
150 mode = Mode::Main;
151 }
152 _ => {}
153 },
154 Mode::SetSampleRate => {
155 if code == Key::Enter {
156 desired_sample_rate = input_buf.parse()?;
157 mode = Mode::Main;
158 }
159 }
160 Mode::SetChannelCount => {
161 if code == Key::Enter {
162 desired_channel_count = input_buf.parse()?;
163 mode = Mode::Main;
164 }
165 }
166 Mode::Export => {
167 if code == Key::Enter {
168 snd_buf.save_to_file(&input_buf)?;
169 mode = Mode::Main;
170 }
171 }
172 },
173 Event::TextEntered { unicode } => match mode {
174 Mode::SetSampleRate | Mode::SetChannelCount => {
175 if unicode.is_ascii_digit() {
176 input_buf.push(unicode);
177 } else if unicode == 0x8 as char {
178 input_buf.pop();
179 }
180 }
181 Mode::Export => {
182 if !unicode.is_ascii_control() {
183 input_buf.push(unicode);
184 } else if unicode == 0x8 as char {
185 input_buf.pop();
186 }
187 }
188 Mode::Main | Mode::SetDevice => {}
189 },
190 _ => {}
191 }
192 }
193 if let Ok(samples) = recv.try_recv() {
194 samp_accum.extend_from_slice(&samples);
195 samp_buf = samples;
196 }
197 rw.clear(Color::rgb(10, 60, 40));
198 let mut writer = TextWriter::new(&font, 20, 0.0, 0.0);
199 macro_rules! w {
200 ($($arg:tt)*) => {
201 writer.write(&format!($($arg)*), &mut rw);
202 }
203 }
204 match mode {
205 Mode::Main => {
206 w!("D - set device, S - set sample rate, C - set channel count, E - export");
207 let s = if started {
208 "Press R to stop recording"
209 } else {
210 "Press R to start recording. Press P to play the recording."
211 };
212 w!("{s}");
213 w!(
214 "{} @ {} Hz\n{} samples, {} channels, {} bytes recorded",
215 driver.device(),
216 driver.sample_rate(),
217 samp_buf.len(),
218 driver.channel_count(),
219 samp_accum.len() * 2,
220 );
221 let mut rect = RectangleShape::new();
222 for (i, &sample) in samp_buf.iter().enumerate() {
223 let ratio = samp_buf.len() as f32 / rw.size().x as f32;
224 rect.set_position((i as f32 / ratio, 300.0));
225 rect.set_size((2.0, sample as f32 / 48.0));
226 rw.draw(&rect);
227 }
228 }
229 Mode::SetDevice => {
230 for (i, dev) in devices.iter().enumerate() {
231 let default_str = if dev == &*default_device {
232 " (default)"
233 } else {
234 ""
235 };
236 let color = if selected_dev_idx == i {
237 Color::YELLOW
238 } else {
239 Color::WHITE
240 };
241 writer.text.set_fill_color(color);
242 w!("{}: {}{default_str}", i + 1, dev.to_str()?);
243 }
244 }
245 Mode::SetSampleRate => {
246 w!("Enter desired sample rate");
247 w!("{input_buf}");
248 }
249 Mode::SetChannelCount => {
250 w!("Enter desired channel count");
251 w!("{input_buf}");
252 }
253 Mode::Export => {
254 w!("Enter filename to export as");
255 w!("{input_buf}");
256 }
257 }
258 rw.display();
259 }
260 Ok(())
261}
21fn main() -> SfResult<()> {
22 example_ensure_right_working_dir();
23
24 let mut rng = SmallRng::seed_from_u64(1);
25
26 // Optional antialiasing
27 let mut aa_level = 0;
28
29 if let Some(arg) = env::args().nth(1) {
30 match arg.parse::<u32>() {
31 Ok(arg_as_num) => aa_level = arg_as_num,
32 Err(e) => println!("Didn't set AA level: {e}"),
33 }
34 }
35
36 // Define some constants
37 let game_width = 800;
38 let game_height = 600;
39 let paddle_size = Vector2f::new(25., 100.);
40 let ball_radius = 10.;
41
42 // Create the window of the application
43 let context_settings = ContextSettings {
44 antialiasing_level: aa_level,
45 ..Default::default()
46 };
47 let mut window = RenderWindow::new(
48 [game_width, game_height],
49 "SFML Pong",
50 Style::CLOSE,
51 &context_settings,
52 )?;
53 let context_settings = window.settings();
54 if context_settings.antialiasing_level > 0 {
55 println!("Using {}xAA", context_settings.antialiasing_level);
56 }
57 window.set_vertical_sync_enabled(true);
58
59 // Load the sounds used in the game
60 let ball_soundbuffer = SoundBuffer::from_file("ball.wav")?;
61 let mut ball_sound = Sound::with_buffer(&ball_soundbuffer);
62
63 // Create the left paddle
64 let mut left_paddle = RectangleShape::new();
65 left_paddle.set_size(paddle_size - Vector2f::new(3., 3.));
66 left_paddle.set_outline_thickness(3.);
67 left_paddle.set_outline_color(Color::BLACK);
68 left_paddle.set_fill_color(Color::rgb(100, 100, 200));
69 left_paddle.set_origin(paddle_size / 2.);
70
71 // Create the right paddle
72 let mut right_paddle = RectangleShape::new();
73 right_paddle.set_size(paddle_size - Vector2f::new(3., 3.));
74 right_paddle.set_outline_thickness(3.);
75 right_paddle.set_outline_color(Color::BLACK);
76 right_paddle.set_fill_color(Color::rgb(200, 100, 100));
77 right_paddle.set_origin(paddle_size / 2.);
78
79 // Create the ball
80 let mut ball = CircleShape::default();
81 ball.set_radius(ball_radius - 3.);
82 ball.set_outline_thickness(3.);
83 ball.set_outline_color(Color::BLACK);
84 ball.set_fill_color(Color::WHITE);
85 ball.set_origin(ball_radius / 2.);
86
87 // Load the text font
88 let font = Font::from_file("sansation.ttf")?;
89
90 // Initialize the pause message
91 let mut pause_message = Text::default();
92 pause_message.set_font(&font);
93 pause_message.set_character_size(40);
94 pause_message.set_position((170., 150.));
95 pause_message.set_fill_color(Color::WHITE);
96 pause_message.set_string("Welcome to SFML pong!\nPress space to start the game");
97
98 // Define the paddles properties
99 let mut ai_timer = Clock::start()?;
100 let paddle_speed = 400.;
101 let mut right_paddle_speed = 0.;
102 let mut ball_speed = 400.;
103 let mut ball_angle = 0.;
104
105 let mut clock = Clock::start()?;
106 let mut is_playing = false;
107 let mut up = false;
108 let mut down = false;
109
110 'mainloop: loop {
111 while let Some(event) = window.poll_event() {
112 match event {
113 Event::Closed
114 | Event::KeyPressed {
115 code: Key::Escape, ..
116 } => break 'mainloop,
117 Event::KeyPressed {
118 code: Key::Space, ..
119 } if !is_playing => {
120 // (re)start the game
121 is_playing = true;
122 ball_speed = 400.0;
123 ball_sound.set_pitch(1.0);
124 clock.restart();
125 // Reset the position of the paddles and ball
126 left_paddle.set_position((10. + paddle_size.x / 2., game_height as f32 / 2.));
127 right_paddle.set_position((
128 game_width as f32 - 10. - paddle_size.x / 2.,
129 game_height as f32 / 2.,
130 ));
131 ball.set_position((game_width as f32 / 2., game_height as f32 / 2.));
132 // Reset the ball angle
133 loop {
134 // Make sure the ball initial angle is not too much vertical
135 ball_angle = rng.random_range(0.0..360.) * 2. * PI / 360.;
136
137 if ball_angle.cos().abs() >= 0.7 {
138 break;
139 }
140 }
141 }
142 Event::KeyPressed { code: Key::Up, .. }
143 | Event::KeyPressed {
144 scan: Scancode::W, ..
145 } => up = true,
146 Event::KeyReleased { code: Key::Up, .. }
147 | Event::KeyReleased {
148 scan: Scancode::W, ..
149 } => up = false,
150 Event::KeyPressed {
151 code: Key::Down, ..
152 }
153 | Event::KeyPressed {
154 scan: Scancode::S, ..
155 } => down = true,
156 Event::KeyReleased {
157 code: Key::Down, ..
158 }
159 | Event::KeyReleased {
160 scan: Scancode::S, ..
161 } => down = false,
162 _ => {}
163 }
164 }
165 if is_playing {
166 let delta_time = clock.restart().as_seconds();
167
168 // Move the player's paddle
169 if up && (left_paddle.position().y - paddle_size.y / 2. > 5.) {
170 left_paddle.move_((0., -paddle_speed * delta_time));
171 }
172 if down && (left_paddle.position().y + paddle_size.y / 2. < game_height as f32 - 5.) {
173 left_paddle.move_((0., paddle_speed * delta_time));
174 }
175
176 // Move the computer's paddle
177 if ((right_paddle_speed < 0.) && (right_paddle.position().y - paddle_size.y / 2. > 5.))
178 || ((right_paddle_speed > 0.)
179 && (right_paddle.position().y + paddle_size.y / 2. < game_height as f32 - 5.))
180 {
181 right_paddle.move_((0., right_paddle_speed * delta_time));
182 }
183
184 // Update the computer's paddle direction according to the ball position
185 if ai_timer.elapsed_time() > AI_REACT_DELAY {
186 ai_timer.restart();
187 if ball.position().y + ball_radius > right_paddle.position().y + paddle_size.y / 2.
188 {
189 right_paddle_speed = paddle_speed;
190 } else if ball.position().y - ball_radius
191 < right_paddle.position().y - paddle_size.y / 2.
192 {
193 right_paddle_speed = -paddle_speed;
194 } else {
195 right_paddle_speed = 0.;
196 }
197 }
198
199 // Move the ball
200 let factor = ball_speed * delta_time;
201 ball.move_((ball_angle.cos() * factor, ball_angle.sin() * factor));
202
203 // Check collisions between the ball and the screen
204 if ball.position().x - ball_radius < 0. {
205 is_playing = false;
206 pause_message.set_string("You lost !\nPress space to restart or\nescape to exit");
207 }
208 if ball.position().x + ball_radius > game_width as f32 {
209 is_playing = false;
210 pause_message.set_string("You won !\nPress space to restart or\nescape to exit");
211 }
212 if ball.position().y - ball_radius < 0. {
213 on_bounce(&mut ball_sound, &mut ball_speed);
214 ball_angle = -ball_angle;
215 let p = ball.position().x;
216 ball.set_position((p, ball_radius + 0.1));
217 }
218 if ball.position().y + ball_radius > game_height as f32 {
219 on_bounce(&mut ball_sound, &mut ball_speed);
220 ball_angle = -ball_angle;
221 let p = ball.position().x;
222 ball.set_position((p, game_height as f32 - ball_radius - 0.1));
223 }
224
225 // Check the collisions between the ball and the paddles
226 // Left Paddle
227 let (ball_pos, paddle_pos) = (ball.position(), left_paddle.position());
228 if ball_pos.x - ball_radius < paddle_pos.x + paddle_size.x / 2.
229 && ball_pos.y + ball_radius >= paddle_pos.y - paddle_size.y / 2.
230 && ball_pos.y - ball_radius <= paddle_pos.y + paddle_size.y / 2.
231 {
232 if ball_pos.y > paddle_pos.y {
233 ball_angle = PI - ball_angle + rng.random_range(0.0..20.) * PI / 180.;
234 } else {
235 ball_angle = PI - ball_angle - rng.random_range(0.0..20.) * PI / 180.;
236 }
237
238 on_bounce(&mut ball_sound, &mut ball_speed);
239 ball.set_position((
240 paddle_pos.x + ball_radius + paddle_size.x / 2. + 0.1,
241 ball_pos.y,
242 ));
243 }
244
245 // Right Paddle
246 let (ball_pos, paddle_pos) = (ball.position(), right_paddle.position());
247 if ball_pos.x + ball_radius > paddle_pos.x - paddle_size.x / 2.
248 && ball_pos.y + ball_radius >= paddle_pos.y - paddle_size.y / 2.
249 && ball_pos.y - ball_radius <= paddle_pos.y + paddle_size.y / 2.
250 {
251 if ball_pos.y > paddle_pos.y {
252 ball_angle = PI - ball_angle + rng.random_range(0.0..20.) * PI / 180.;
253 } else {
254 ball_angle = PI - ball_angle - rng.random_range(0.0..20.) * PI / 180.;
255 }
256
257 on_bounce(&mut ball_sound, &mut ball_speed);
258 ball.set_position((
259 paddle_pos.x - ball_radius - paddle_size.x / 2. - 0.1,
260 ball_pos.y,
261 ));
262 }
263 }
264 // Clear the window
265 window.clear(Color::rgb(50, 200, 50));
266
267 if is_playing {
268 // Draw the paddles and the ball
269 window.draw(&left_paddle);
270 window.draw(&right_paddle);
271 window.draw(&ball);
272 } else {
273 // Draw the pause message
274 window.draw(&pause_message);
275 }
276
277 // Display things on screen
278 window.display()
279 }
280 Ok(())
281}
Source§impl Sound<'_>
Playback
impl Sound<'_>
Playback
Sourcepub fn play(&mut self)
pub fn play(&mut self)
Start or resume playing a sound
This function starts the sound 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 sound is played.
Examples found in repository?
More examples
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}
55fn main() -> SfResult<()> {
56 example_ensure_right_working_dir();
57
58 let mut tex_holder = ResourceHolder::<Texture, _>::default();
59 tex_holder.load("frank", "frank.jpeg")?;
60 let mut sb_holder = ResourceHolder::<SoundBuffer, _>::default();
61 sb_holder.load("canary", "canary.wav")?;
62 let mut rw = RenderWindow::new(
63 (800, 600),
64 "Resource holder test",
65 Style::CLOSE,
66 &Default::default(),
67 )?;
68 rw.set_vertical_sync_enabled(true);
69 let mut sound = Sound::with_buffer(sb_holder.get("canary"));
70 sound.play();
71 while rw.is_open() {
72 while let Some(ev) = rw.poll_event() {
73 match ev {
74 Event::Closed
75 | Event::KeyPressed {
76 code: Key::Escape, ..
77 } => rw.close(),
78 _ => {}
79 }
80 }
81 rw.clear(Color::BLACK);
82 rw.draw(&Sprite::with_texture(tex_holder.get("frank")));
83 rw.display();
84 }
85 Ok(())
86}
12fn main() -> Result<(), Box<dyn Error>> {
13 // Check that the device can capture audio
14 assert!(
15 capture::is_available(),
16 "Sorry, audio capture is not supported by your system"
17 );
18 let default_device = capture::default_device();
19 let devices = capture::available_devices();
20 println!("{} recording devices available:", devices.len());
21 for (i, device) in devices.iter().enumerate() {
22 let def_str = if device == &*default_device {
23 " (default)"
24 } else {
25 ""
26 };
27 println!("Device {i}: {device}{def_str}");
28 }
29
30 // Choose the sample rate
31 println!(
32 "Please input device and sample rate, then press enter\n\
33 Example:\n\
34 1 22050 # record at 22050 Hz on device 1\n\
35 Default (on empty input) is device 0 and 44100 Hz (CD quality)"
36 );
37 let stdin = std::io::stdin();
38 let mut reader = stdin.lock();
39 let mut line = String::new();
40 reader.read_line(&mut line)?;
41 let input = line.trim_end();
42 let mut tokens = input.split_whitespace();
43 let device_idx = if let Some(token) = tokens.next() {
44 match token.parse::<usize>() {
45 Ok(value) => value,
46 Err(e) => return Err(format!("Input is not valid: {e}").into()),
47 }
48 } else {
49 0
50 };
51 let sample_rate = if let Some(token) = tokens.next() {
52 match token.parse::<u32>() {
53 Ok(value) => value,
54 Err(e) => return Err(format!("Input is not valid: {e}").into()),
55 }
56 } else {
57 44_100
58 };
59
60 // Here we'll use an integrated custom recorder,
61 // which saves the captured data into a SoundBuffer
62 let mut recorder = SoundBufferRecorder::new();
63 match devices.get(device_idx) {
64 Some(device) => {
65 recorder.set_device(device.to_str()?)?;
66 }
67 None => {
68 eprintln!("No device with index {device_idx}");
69 }
70 }
71
72 // Audio capture is done in a separate thread,
73 // so we can block the main thread while it is capturing
74 recorder.start(sample_rate)?;
75 println!(
76 "Recording on device {} @ {} Hz...\nPress enter to stop",
77 recorder.device().to_str().unwrap_or("<invalid utf-8>"),
78 recorder.sample_rate()
79 );
80 reader.read_line(&mut String::new())?;
81 recorder.stop();
82
83 // Get the buffer containing the captured data
84 let buffer = recorder.buffer();
85
86 // Display captured sound information
87 println!("Sound information :");
88 println!(" {} seconds", buffer.duration().as_seconds());
89 println!(" {} samples / sec", buffer.sample_rate());
90 println!(" {} channels", buffer.channel_count());
91
92 // Choose what to do with the recorded sound data
93 print!("What do you want to do with captured sound (p = play, s = save) ? ");
94 let _ = std::io::stdout().flush();
95 let mut resp = String::new();
96 reader.read_line(&mut resp)?;
97
98 if resp.trim() == "s" {
99 // Choose a filename
100 println!("Choose the file to create: ");
101 let mut filename = String::new();
102 reader.read_line(&mut filename)?;
103
104 // Save the buffer
105 if buffer.save_to_file(filename.trim()).is_err() {
106 eprintln!("Error saving buffer to {}!", filename.trim());
107 }
108 } else {
109 let mut sound = Sound::with_buffer(buffer);
110
111 sound.play();
112
113 while sound.status() == SoundStatus::PLAYING {
114 // Display the playing position
115 print!(
116 "\rPlaying... {:.2} sec",
117 sound.playing_offset().as_seconds()
118 );
119 let _ = std::io::stdout().flush();
120 // Leave some CPU time for other processes
121 sleep(Time::milliseconds(100));
122 }
123 }
124
125 // Finished
126 println!("\nDone!");
127 Ok(())
128}
65fn main() -> Result<(), Box<dyn Error>> {
66 example_ensure_right_working_dir();
67
68 assert!(
69 capture::is_available(),
70 "Sorry, audio capture is not supported by your system"
71 );
72 let default_device = capture::default_device();
73 let devices = capture::available_devices();
74 let mut rw = RenderWindow::new(
75 (800, 600),
76 "Custom sound recorder",
77 Style::CLOSE,
78 &Default::default(),
79 )?;
80 rw.set_vertical_sync_enabled(true);
81 let font = Font::from_file("sansation.ttf")?;
82 let (mut rec, recv) = MyRecorder::new();
83 let mut samp_buf = Vec::new();
84 let mut driver = SoundRecorderDriver::new(&mut rec);
85 let mut started = false;
86 let mut snd_buf = SoundBuffer::new()?;
87 let mut samp_accum = Vec::new();
88 let mut sound = Some(Sound::new());
89 let mut selected_dev_idx = 0;
90 let mut mode = Mode::Main;
91 let mut input_buf = String::new();
92 let mut desired_sample_rate = 44_100;
93 let mut desired_channel_count = 2;
94
95 while rw.is_open() {
96 while let Some(ev) = rw.poll_event() {
97 match ev {
98 Event::Closed => rw.close(),
99 Event::KeyPressed { code, .. } => match mode {
100 Mode::Main => match code {
101 Key::R => {
102 if started {
103 driver.stop();
104 sound = None;
105 snd_buf.load_from_samples(
106 &samp_accum[..],
107 desired_channel_count,
108 desired_sample_rate,
109 )?;
110 samp_accum.clear();
111 started = false;
112 } else {
113 driver.set_device(devices[selected_dev_idx].to_str()?)?;
114 driver.set_channel_count(desired_channel_count);
115 driver.start(desired_sample_rate)?;
116 started = true;
117 }
118 }
119 Key::P => {
120 if !started {
121 let sound = sound.insert(Sound::with_buffer(&snd_buf));
122 sound.play();
123 }
124 }
125 Key::D => mode = Mode::SetDevice,
126 Key::S => {
127 input_buf = desired_sample_rate.to_string();
128 mode = Mode::SetSampleRate;
129 }
130 Key::C => {
131 input_buf = desired_channel_count.to_string();
132 mode = Mode::SetChannelCount;
133 }
134 Key::E => {
135 input_buf = "export.wav".to_string();
136 mode = Mode::Export;
137 }
138 _ => {}
139 },
140 Mode::SetDevice => match code {
141 Key::Up => {
142 selected_dev_idx -= selected_dev_idx.saturating_sub(1);
143 }
144 Key::Down => {
145 if selected_dev_idx + 1 < devices.len() {
146 selected_dev_idx += 1;
147 }
148 }
149 Key::Enter | Key::Escape => {
150 mode = Mode::Main;
151 }
152 _ => {}
153 },
154 Mode::SetSampleRate => {
155 if code == Key::Enter {
156 desired_sample_rate = input_buf.parse()?;
157 mode = Mode::Main;
158 }
159 }
160 Mode::SetChannelCount => {
161 if code == Key::Enter {
162 desired_channel_count = input_buf.parse()?;
163 mode = Mode::Main;
164 }
165 }
166 Mode::Export => {
167 if code == Key::Enter {
168 snd_buf.save_to_file(&input_buf)?;
169 mode = Mode::Main;
170 }
171 }
172 },
173 Event::TextEntered { unicode } => match mode {
174 Mode::SetSampleRate | Mode::SetChannelCount => {
175 if unicode.is_ascii_digit() {
176 input_buf.push(unicode);
177 } else if unicode == 0x8 as char {
178 input_buf.pop();
179 }
180 }
181 Mode::Export => {
182 if !unicode.is_ascii_control() {
183 input_buf.push(unicode);
184 } else if unicode == 0x8 as char {
185 input_buf.pop();
186 }
187 }
188 Mode::Main | Mode::SetDevice => {}
189 },
190 _ => {}
191 }
192 }
193 if let Ok(samples) = recv.try_recv() {
194 samp_accum.extend_from_slice(&samples);
195 samp_buf = samples;
196 }
197 rw.clear(Color::rgb(10, 60, 40));
198 let mut writer = TextWriter::new(&font, 20, 0.0, 0.0);
199 macro_rules! w {
200 ($($arg:tt)*) => {
201 writer.write(&format!($($arg)*), &mut rw);
202 }
203 }
204 match mode {
205 Mode::Main => {
206 w!("D - set device, S - set sample rate, C - set channel count, E - export");
207 let s = if started {
208 "Press R to stop recording"
209 } else {
210 "Press R to start recording. Press P to play the recording."
211 };
212 w!("{s}");
213 w!(
214 "{} @ {} Hz\n{} samples, {} channels, {} bytes recorded",
215 driver.device(),
216 driver.sample_rate(),
217 samp_buf.len(),
218 driver.channel_count(),
219 samp_accum.len() * 2,
220 );
221 let mut rect = RectangleShape::new();
222 for (i, &sample) in samp_buf.iter().enumerate() {
223 let ratio = samp_buf.len() as f32 / rw.size().x as f32;
224 rect.set_position((i as f32 / ratio, 300.0));
225 rect.set_size((2.0, sample as f32 / 48.0));
226 rw.draw(&rect);
227 }
228 }
229 Mode::SetDevice => {
230 for (i, dev) in devices.iter().enumerate() {
231 let default_str = if dev == &*default_device {
232 " (default)"
233 } else {
234 ""
235 };
236 let color = if selected_dev_idx == i {
237 Color::YELLOW
238 } else {
239 Color::WHITE
240 };
241 writer.text.set_fill_color(color);
242 w!("{}: {}{default_str}", i + 1, dev.to_str()?);
243 }
244 }
245 Mode::SetSampleRate => {
246 w!("Enter desired sample rate");
247 w!("{input_buf}");
248 }
249 Mode::SetChannelCount => {
250 w!("Enter desired channel count");
251 w!("{input_buf}");
252 }
253 Mode::Export => {
254 w!("Enter filename to export as");
255 w!("{input_buf}");
256 }
257 }
258 rw.display();
259 }
260 Ok(())
261}
Source§impl<'buf> Sound<'buf>
Query properties
impl<'buf> Sound<'buf>
Query properties
Sourcepub fn is_looping(&self) -> bool
pub fn is_looping(&self) -> bool
Tell whether or not a sound is in loop mode
Return true if the sound is looping, false otherwise
Sourcepub fn status(&self) -> SoundStatus
pub fn status(&self) -> SoundStatus
Get the current status of a sound (stopped, paused, playing)
Return current status
Examples found in repository?
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}
More examples
12fn main() -> Result<(), Box<dyn Error>> {
13 // Check that the device can capture audio
14 assert!(
15 capture::is_available(),
16 "Sorry, audio capture is not supported by your system"
17 );
18 let default_device = capture::default_device();
19 let devices = capture::available_devices();
20 println!("{} recording devices available:", devices.len());
21 for (i, device) in devices.iter().enumerate() {
22 let def_str = if device == &*default_device {
23 " (default)"
24 } else {
25 ""
26 };
27 println!("Device {i}: {device}{def_str}");
28 }
29
30 // Choose the sample rate
31 println!(
32 "Please input device and sample rate, then press enter\n\
33 Example:\n\
34 1 22050 # record at 22050 Hz on device 1\n\
35 Default (on empty input) is device 0 and 44100 Hz (CD quality)"
36 );
37 let stdin = std::io::stdin();
38 let mut reader = stdin.lock();
39 let mut line = String::new();
40 reader.read_line(&mut line)?;
41 let input = line.trim_end();
42 let mut tokens = input.split_whitespace();
43 let device_idx = if let Some(token) = tokens.next() {
44 match token.parse::<usize>() {
45 Ok(value) => value,
46 Err(e) => return Err(format!("Input is not valid: {e}").into()),
47 }
48 } else {
49 0
50 };
51 let sample_rate = if let Some(token) = tokens.next() {
52 match token.parse::<u32>() {
53 Ok(value) => value,
54 Err(e) => return Err(format!("Input is not valid: {e}").into()),
55 }
56 } else {
57 44_100
58 };
59
60 // Here we'll use an integrated custom recorder,
61 // which saves the captured data into a SoundBuffer
62 let mut recorder = SoundBufferRecorder::new();
63 match devices.get(device_idx) {
64 Some(device) => {
65 recorder.set_device(device.to_str()?)?;
66 }
67 None => {
68 eprintln!("No device with index {device_idx}");
69 }
70 }
71
72 // Audio capture is done in a separate thread,
73 // so we can block the main thread while it is capturing
74 recorder.start(sample_rate)?;
75 println!(
76 "Recording on device {} @ {} Hz...\nPress enter to stop",
77 recorder.device().to_str().unwrap_or("<invalid utf-8>"),
78 recorder.sample_rate()
79 );
80 reader.read_line(&mut String::new())?;
81 recorder.stop();
82
83 // Get the buffer containing the captured data
84 let buffer = recorder.buffer();
85
86 // Display captured sound information
87 println!("Sound information :");
88 println!(" {} seconds", buffer.duration().as_seconds());
89 println!(" {} samples / sec", buffer.sample_rate());
90 println!(" {} channels", buffer.channel_count());
91
92 // Choose what to do with the recorded sound data
93 print!("What do you want to do with captured sound (p = play, s = save) ? ");
94 let _ = std::io::stdout().flush();
95 let mut resp = String::new();
96 reader.read_line(&mut resp)?;
97
98 if resp.trim() == "s" {
99 // Choose a filename
100 println!("Choose the file to create: ");
101 let mut filename = String::new();
102 reader.read_line(&mut filename)?;
103
104 // Save the buffer
105 if buffer.save_to_file(filename.trim()).is_err() {
106 eprintln!("Error saving buffer to {}!", filename.trim());
107 }
108 } else {
109 let mut sound = Sound::with_buffer(buffer);
110
111 sound.play();
112
113 while sound.status() == SoundStatus::PLAYING {
114 // Display the playing position
115 print!(
116 "\rPlaying... {:.2} sec",
117 sound.playing_offset().as_seconds()
118 );
119 let _ = std::io::stdout().flush();
120 // Leave some CPU time for other processes
121 sleep(Time::milliseconds(100));
122 }
123 }
124
125 // Finished
126 println!("\nDone!");
127 Ok(())
128}
Sourcepub fn playing_offset(&self) -> Time
pub fn playing_offset(&self) -> Time
Get the current playing position of a sound
Return the current playing position
Examples found in repository?
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}
More examples
12fn main() -> Result<(), Box<dyn Error>> {
13 // Check that the device can capture audio
14 assert!(
15 capture::is_available(),
16 "Sorry, audio capture is not supported by your system"
17 );
18 let default_device = capture::default_device();
19 let devices = capture::available_devices();
20 println!("{} recording devices available:", devices.len());
21 for (i, device) in devices.iter().enumerate() {
22 let def_str = if device == &*default_device {
23 " (default)"
24 } else {
25 ""
26 };
27 println!("Device {i}: {device}{def_str}");
28 }
29
30 // Choose the sample rate
31 println!(
32 "Please input device and sample rate, then press enter\n\
33 Example:\n\
34 1 22050 # record at 22050 Hz on device 1\n\
35 Default (on empty input) is device 0 and 44100 Hz (CD quality)"
36 );
37 let stdin = std::io::stdin();
38 let mut reader = stdin.lock();
39 let mut line = String::new();
40 reader.read_line(&mut line)?;
41 let input = line.trim_end();
42 let mut tokens = input.split_whitespace();
43 let device_idx = if let Some(token) = tokens.next() {
44 match token.parse::<usize>() {
45 Ok(value) => value,
46 Err(e) => return Err(format!("Input is not valid: {e}").into()),
47 }
48 } else {
49 0
50 };
51 let sample_rate = if let Some(token) = tokens.next() {
52 match token.parse::<u32>() {
53 Ok(value) => value,
54 Err(e) => return Err(format!("Input is not valid: {e}").into()),
55 }
56 } else {
57 44_100
58 };
59
60 // Here we'll use an integrated custom recorder,
61 // which saves the captured data into a SoundBuffer
62 let mut recorder = SoundBufferRecorder::new();
63 match devices.get(device_idx) {
64 Some(device) => {
65 recorder.set_device(device.to_str()?)?;
66 }
67 None => {
68 eprintln!("No device with index {device_idx}");
69 }
70 }
71
72 // Audio capture is done in a separate thread,
73 // so we can block the main thread while it is capturing
74 recorder.start(sample_rate)?;
75 println!(
76 "Recording on device {} @ {} Hz...\nPress enter to stop",
77 recorder.device().to_str().unwrap_or("<invalid utf-8>"),
78 recorder.sample_rate()
79 );
80 reader.read_line(&mut String::new())?;
81 recorder.stop();
82
83 // Get the buffer containing the captured data
84 let buffer = recorder.buffer();
85
86 // Display captured sound information
87 println!("Sound information :");
88 println!(" {} seconds", buffer.duration().as_seconds());
89 println!(" {} samples / sec", buffer.sample_rate());
90 println!(" {} channels", buffer.channel_count());
91
92 // Choose what to do with the recorded sound data
93 print!("What do you want to do with captured sound (p = play, s = save) ? ");
94 let _ = std::io::stdout().flush();
95 let mut resp = String::new();
96 reader.read_line(&mut resp)?;
97
98 if resp.trim() == "s" {
99 // Choose a filename
100 println!("Choose the file to create: ");
101 let mut filename = String::new();
102 reader.read_line(&mut filename)?;
103
104 // Save the buffer
105 if buffer.save_to_file(filename.trim()).is_err() {
106 eprintln!("Error saving buffer to {}!", filename.trim());
107 }
108 } else {
109 let mut sound = Sound::with_buffer(buffer);
110
111 sound.play();
112
113 while sound.status() == SoundStatus::PLAYING {
114 // Display the playing position
115 print!(
116 "\rPlaying... {:.2} sec",
117 sound.playing_offset().as_seconds()
118 );
119 let _ = std::io::stdout().flush();
120 // Leave some CPU time for other processes
121 sleep(Time::milliseconds(100));
122 }
123 }
124
125 // Finished
126 println!("\nDone!");
127 Ok(())
128}
Sourcepub fn buffer(&self) -> Option<&'buf SoundBuffer>
pub fn buffer(&self) -> Option<&'buf SoundBuffer>
Get the audio buffer attached to a sound
Return an option to Sound buffer attached to the sound or None
Source§impl<'buf> Sound<'buf>
Set properties
impl<'buf> Sound<'buf>
Set properties
Sourcepub fn set_looping(&mut self, looping: bool)
pub fn set_looping(&mut self, looping: bool)
Sets whether this sound should loop or not.
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 sound
The playing position can be changed when the sound is either paused or playing.
§Arguments
- timeOffset - New playing position
Sourcepub fn set_buffer(&mut self, buffer: &'buf SoundBuffer)
pub fn set_buffer(&mut self, buffer: &'buf SoundBuffer)
Set the source buffer containing the audio data to play
§Arguments
- buffer - Sound buffer to attach to the sound