From e04a3cc4e9a43902f9640c628654095f284fd332 Mon Sep 17 00:00:00 2001 From: Daisuke Murase Date: Mon, 16 Dec 2024 21:43:38 -0800 Subject: [PATCH] Fix `play_from_disk` example to work with recent SDK (#529) * fix compilation error * fix wave header parser to allow other chunks before the data chunk --- examples/play_from_disk/src/main.rs | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/examples/play_from_disk/src/main.rs b/examples/play_from_disk/src/main.rs index b96d4e5c7..21f0de17a 100644 --- a/examples/play_from_disk/src/main.rs +++ b/examples/play_from_disk/src/main.rs @@ -7,10 +7,10 @@ use livekit::{ }, Room, RoomOptions, }; -use std::{env, mem::size_of, sync::Arc, time::Duration}; +use std::{env, io::SeekFrom, mem::size_of, sync::Arc, time::Duration}; use std::{error::Error, io}; use thiserror::Error; -use tokio::io::{AsyncRead, AsyncReadExt, BufReader}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeek, AsyncSeekExt, BufReader}; #[derive(Debug, Error)] pub enum WavError { @@ -20,7 +20,7 @@ pub enum WavError { Io(#[from] io::Error), } -pub struct WavReader { +pub struct WavReader { reader: R, } @@ -39,7 +39,7 @@ pub struct WavHeader { bits_per_sample: u16, } -impl WavReader { +impl WavReader { pub fn new(reader: R) -> Self { Self { reader } } @@ -76,8 +76,19 @@ impl WavReader { let byte_rate = self.reader.read_u32_le().await?; let block_align = self.reader.read_u16_le().await?; let bits_per_sample = self.reader.read_u16_le().await?; - self.reader.read_exact(&mut data_chunk).await?; - let data_size = self.reader.read_u32_le().await?; + + let mut data_size = 0; + loop { + self.reader.read_exact(&mut data_chunk).await?; + data_size = self.reader.read_u32_le().await?; + + if &data_chunk == b"data" { + break; + } else { + // skip non data chunks + self.reader.seek(SeekFrom::Current(data_size.into())).await?; + } + } if &data_chunk != b"data" { return Err(WavError::InvalidHeader("Invalid data chunk")); @@ -123,12 +134,13 @@ async fn main() -> Result<(), Box> { .await .unwrap(); let room = Arc::new(room); - log::info!("Connected to room: {} - {}", room.name(), room.sid()); + log::info!("Connected to room: {} - {}", room.name(), room.sid().await); let source = NativeAudioSource::new( AudioSourceOptions::default(), header.sample_rate, header.num_channels as u32, + 1000, ); let track = LocalAudioTrack::create_audio_track("file", RtcAudioSource::Native(source.clone()));