Upsample audio from source_rate to target_rate using linear interpolation.
(samples: &[f32], source_rate: usize, target_rate: usize)
| 368 | |
| 369 | /// Upsample audio from source_rate to target_rate using linear interpolation. |
| 370 | pub fn upsample(samples: &[f32], source_rate: usize, target_rate: usize) -> Vec<f32> { |
| 371 | if source_rate == target_rate { |
| 372 | return samples.to_vec(); |
| 373 | } |
| 374 | let ratio = target_rate as f64 / source_rate as f64; |
| 375 | let new_len = (samples.len() as f64 * ratio) as usize; |
| 376 | let mut output = Vec::with_capacity(new_len); |
| 377 | for i in 0..new_len { |
| 378 | let src_pos = i as f64 / ratio; |
| 379 | let idx = src_pos as usize; |
| 380 | let frac = (src_pos - idx as f64) as f32; |
| 381 | let s0 = samples.get(idx).copied().unwrap_or(0.0); |
| 382 | let s1 = samples.get(idx + 1).copied().unwrap_or(s0); |
| 383 | output.push(s0 + frac * (s1 - s0)); |
| 384 | } |
| 385 | output |
| 386 | } |
| 387 | |
| 388 | /// Save audio samples as WAV file (16-bit PCM). |
| 389 | /// |