Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

feat: audio streaming (#557)

Ezra Ellette8628c650ae6b
diff --git a/screenpipe-audio/benches/record_and_transcribe_benchmark.rs b/screenpipe-audio/benches/record_and_transcribe_benchmark.rs
index da01bec3c..b50cb1cdc 100644
--- a/screenpipe-audio/benches/record_and_transcribe_benchmark.rs
+++ b/screenpipe-audio/benches/record_and_transcribe_benchmark.rs
@@ -2,7 +2,7 @@ use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criteri
use screenpipe_audio::vad_engine::VadSensitivity;
use screenpipe_audio::{
create_whisper_channel, default_input_device, record_and_transcribe, AudioDevice, AudioInput,
- AudioTranscriptionEngine,
+ AudioStream, AudioTranscriptionEngine,
};
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
@@ -57,9 +57,13 @@ fn bench_record_and_transcribe(c: &mut Criterion) {
let (audio_device, _, whisper_sender, is_running) = setup_test().await;
let duration = Duration::from_secs(5); // 5 seconds of recording
+ let audio_stream = AudioStream::from_device(audio_device, is_running.clone())
+ .await
+ .unwrap();
+
let start = std::time::Instant::now();
let result = record_and_transcribe(
- black_box(audio_device),
+ black_box(Arc::new(audio_stream)),
black_box(duration),
black_box(whisper_sender),
black_box(is_running),
diff --git a/screenpipe-audio/src/bin/screenpipe-audio-forever.rs b/screenpipe-audio/src/bin/screenpipe-audio-forever.rs
index c1c533c98..1441b3e32 100644
--- a/screenpipe-audio/src/bin/screenpipe-audio-forever.rs
+++ b/screenpipe-audio/src/bin/screenpipe-audio-forever.rs
@@ -9,6 +9,7 @@ use screenpipe_audio::parse_audio_device;
use screenpipe_audio::record_and_transcribe;
use screenpipe_audio::vad_engine::VadSensitivity;
use screenpipe_audio::AudioDevice;
+use screenpipe_audio::AudioStream;
use screenpipe_audio::AudioTranscriptionEngine;
use screenpipe_audio::VadEngineEnum;
use screenpipe_core::Language;
@@ -96,33 +97,40 @@ async fn main() -> Result<()> {
languages,
)
.await?;
+
+ let whisper_sender_clone = whisper_sender.clone();
// Spawn threads for each device
let _recording_threads: Vec<_> = devices
.into_iter()
.enumerate()
.map(|(i, device)| {
- let device = Arc::new(device);
- let whisper_sender = whisper_sender.clone();
-
- let device_control = Arc::new(AtomicBool::new(true));
-
- tokio::spawn(async move {
- loop {
- let result = record_and_transcribe(
- Arc::clone(&device),
- chunk_duration,
- whisper_sender.clone(),
- Arc::clone(&device_control),
- )
- .await;
-
- if let Err(e) = result {
- eprintln!("Error in recording thread {}: {:?}", i, e);
- // Optionally add a short delay before retrying
- tokio::time::sleep(Duration::from_secs(1)).await;
+ let whisper_sender = whisper_sender_clone.clone();
+ async move {
+ let device = Arc::new(device);
+ let device_control = Arc::new(AtomicBool::new(true));
+
+ let audio_stream = AudioStream::from_device(device.clone(), device_control.clone())
+ .await
+ .unwrap();
+
+ tokio::spawn(async move {
+ loop {
+ let result = record_and_transcribe(
+ Arc::new(audio_stream.clone()),
+ chunk_duration,
+ whisper_sender.clone(),
+ Arc::clone(&device_control),
+ )
+ .await;
+
+ if let Err(e) = result {
+ eprintln!("Error in recording thread {}: {:?}", i, e);
+ // Optionally add a short delay before retrying
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ }
}
- }
- })
+ })
+ }
})
.collect();
diff --git a/screenpipe-audio/src/bin/screenpipe-audio.rs b/screenpipe-audio/src/bin/screenpipe-audio.rs
index 22424aad0..755fe61f6 100644
--- a/screenpipe-audio/src/bin/screenpipe-audio.rs
+++ b/screenpipe-audio/src/bin/screenpipe-audio.rs
@@ -9,6 +9,7 @@ use screenpipe_audio::parse_audio_device;
use screenpipe_audio::record_and_transcribe;
use screenpipe_audio::vad_engine::VadSensitivity;
use screenpipe_audio::AudioDevice;
+use screenpipe_audio::AudioStream;
use screenpipe_audio::AudioTranscriptionEngine;
use screenpipe_audio::VadEngineEnum;
use screenpipe_core::Language;
@@ -112,9 +113,13 @@ async fn main() -> Result<()> {
tokio::spawn(async move {
let device_control_clone = Arc::clone(&device_control);
let device_clone_2 = Arc::clone(&device_clone);
+ let audio_stream =
+ AudioStream::from_device(device_clone_2, device_control_clone.clone())
+ .await
+ .unwrap();
record_and_transcribe(
- device_clone_2,
+ Arc::new(audio_stream),
chunk_duration,
whisper_sender,
device_control_clone,
diff --git a/screenpipe-audio/src/core.rs b/screenpipe-audio/src/core.rs
index 5a96f1a5b..b2c4a569b 100644
--- a/screenpipe-audio/src/core.rs
+++ b/screenpipe-audio/src/core.rs
@@ -3,13 +3,14 @@ use crate::AudioInput;
use anyhow::{anyhow, Result};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::StreamError;
-use crossbeam::queue::ArrayQueue;
use log::{debug, error, info, warn};
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::mpsc;
use std::sync::Arc;
use std::time::Duration;
-use std::{fmt, thread}; // Note: We're using parking_lot for better performance
+use std::{fmt, thread};
+use tokio::sync::{broadcast, oneshot};
#[derive(Clone, Debug, PartialEq)]
pub enum AudioTranscriptionEngine {
@@ -159,176 +160,57 @@ async fn get_device_and_config(
}
pub async fn record_and_transcribe(
- audio_device: Arc<AudioDevice>,
+ audio_stream: Arc<AudioStream>,
duration: Duration,
whisper_sender: crossbeam::channel::Sender<AudioInput>,
is_running: Arc<AtomicBool>,
) -> Result<()> {
- let (cpal_audio_device, config) = get_device_and_config(&audio_device).await?;
- let sample_rate = config.sample_rate().0;
- let channels = config.channels();
+ let mut receiver = audio_stream.subscribe().await;
- debug!(
- "Audio device config: sample_rate={}, channels={}",
- sample_rate, channels
+ info!(
+ "starting continuous recording for {} ({}s segments)",
+ audio_stream.device.to_string(),
+ duration.as_secs()
);
- // Create an ArrayQueue with a capacity of 100 chunks (adjust as needed)
- let audio_queue = Arc::new(ArrayQueue::new(100));
- let audio_queue_clone = Arc::clone(&audio_queue);
-
- let is_running_weak = Arc::downgrade(&is_running);
- let is_running_weak_2 = Arc::downgrade(&is_running);
- let is_running_weak_3 = Arc::downgrade(&is_running);
- let is_running_weak_4 = Arc::downgrade(&is_running);
-
- // Define the error callback function
- let error_callback = move |err: StreamError| {
- error!("An error occurred on the audio stream: {}", err);
- if err.to_string().contains("device is no longer valid") {
- warn!("Audio device disconnected. Stopping recording.");
- if let Some(arc) = is_running_weak_2.upgrade() {
- arc.store(false, Ordering::Relaxed);
- }
- }
- };
+ const OVERLAP_SECONDS: usize = 2;
+ let mut collected_audio = Vec::new();
+ let sample_rate = audio_stream.device_config.sample_rate().0 as usize;
+ // let channels = audio_stream.device_config.channels() as usize;
+ let overlap_samples = OVERLAP_SECONDS * sample_rate; // audio is mono otherwise * by # of channels
- // Spawn a thread to handle the non-Send stream
- let audio_handle = thread::spawn(move || {
- let stream = match config.sample_format() {
- cpal::SampleFormat::I8 => cpal_audio_device.build_input_stream(
- &config.into(),
- move |data: &[i8], _: &_| {
- if is_running_weak_3
- .upgrade()
- .map_or(false, |arc| arc.load(Ordering::Relaxed))
- {
- let mono = audio_to_mono(bytemuck::cast_slice(data), channels);
-
- let _ = audio_queue_clone.push(mono);
- }
- },
- error_callback,
- None,
- ),
- cpal::SampleFormat::I16 => cpal_audio_device.build_input_stream(
- &config.into(),
- move |data: &[i16], _: &_| {
- if is_running_weak_3
- .upgrade()
- .map_or(false, |arc| arc.load(Ordering::Relaxed))
- {
- let mono = audio_to_mono(bytemuck::cast_slice(data), channels);
-
- let _ = audio_queue_clone.push(mono);
- }
- },
- error_callback,
- None,
- ),
- cpal::SampleFormat::I32 => cpal_audio_device.build_input_stream(
- &config.into(),
- move |data: &[i32], _: &_| {
- if is_running_weak_3
- .upgrade()
- .map_or(false, |arc| arc.load(Ordering::Relaxed))
- {
- let mono = audio_to_mono(bytemuck::cast_slice(data), channels);
-
- let _ = audio_queue_clone.push(mono);
- }
- },
- error_callback,
- None,
- ),
- cpal::SampleFormat::F32 => cpal_audio_device.build_input_stream(
- &config.into(),
- move |data: &[f32], _: &_| {
- if is_running_weak_3
- .upgrade()
- .map_or(false, |arc| arc.load(Ordering::Relaxed))
- {
- let mono = audio_to_mono(data, channels);
-
- let _ = audio_queue_clone.push(mono);
- }
- },
- error_callback,
- None,
- ),
- _ => {
- error!("Unsupported sample format: {:?}", config.sample_format());
- return;
- }
- };
+ while is_running.load(Ordering::Relaxed) {
+ let start_time = tokio::time::Instant::now();
- match stream {
- Ok(s) => {
- if let Err(e) = s.play() {
- error!("Failed to play stream: {}", e);
- }
- // Keep the stream alive until the recording is done
- while is_running_weak
- .upgrade()
- .map_or(false, |arc| arc.load(Ordering::Relaxed))
- {
- std::thread::sleep(Duration::from_millis(100));
- }
- s.pause().ok();
- drop(s);
+ while start_time.elapsed() < duration && is_running.load(Ordering::Relaxed) {
+ match tokio::time::timeout(Duration::from_millis(100), receiver.recv()).await {
+ Ok(Ok(chunk)) => collected_audio.extend(chunk),
+ Ok(Err(e)) => error!("error receiving audio data: {}", e),
+ Err(_) => {} // Timeout, continue loop
}
- Err(e) => error!("Failed to build input stream: {}", e),
}
- });
- info!(
- "Recording {} for {} seconds",
- audio_device.to_string(),
- duration.as_secs()
- );
- // Spawn another thread to collect audio data
- let collector_handle = tokio::spawn(async move {
- let mut collected_audio = Vec::new();
- while is_running_weak_4
- .upgrade()
- .map_or(false, |arc| arc.load(Ordering::Relaxed))
- {
- while let Some(chunk) = audio_queue.pop() {
- collected_audio.extend(chunk);
+ if !collected_audio.is_empty() {
+ debug!("sending audio segment to audio model");
+ if let Err(e) = whisper_sender.send(AudioInput {
+ data: Arc::new(collected_audio.clone()),
+ device: audio_stream.device.clone(),
+ sample_rate: audio_stream.device_config.sample_rate().0,
+ channels: audio_stream.device_config.channels(),
+ }) {
+ error!("failed to send audio to audio model: {}", e);
}
- tokio::time::sleep(Duration::from_millis(10)).await;
- }
- collected_audio
- });
+ debug!("sent audio segment to audio model");
- // Wait for the duration
- tokio::time::sleep(duration).await;
-
- // Signal the recording to stop
- is_running.store(false, Ordering::Relaxed);
-
- // Wait for the audio thread to finish
- if let Err(e) = audio_handle.join() {
- error!("error joining audio thread: {:?}", e);
- }
-
- // Collect the final audio data
- let audio_data = collector_handle.await.unwrap_or_else(|e| {
- error!("error joining collector thread: {:?}", e);
- Vec::new()
- });
-
- debug!("sending audio to audio model");
- if let Err(e) = whisper_sender.send(AudioInput {
- data: Arc::new(audio_data),
- device: audio_device.clone(),
- sample_rate,
- channels,
- }) {
- error!("failed to send audio to audio model: {}", e);
+ // Reset collected audio to the last two seconds of recorded audio
+ if collected_audio.len() > overlap_samples {
+ collected_audio =
+ collected_audio.split_off(collected_audio.len() - overlap_samples);
+ }
+ }
}
- debug!("sent audio to audio model");
+ info!("stopped recording for {}", audio_stream.device.to_string());
Ok(())
}
@@ -454,3 +336,144 @@ pub fn trigger_audio_permission() -> Result<()> {
Ok(())
}
+
+#[derive(Clone)]
+pub struct AudioStream {
+ pub device: Arc<AudioDevice>,
+ pub device_config: cpal::SupportedStreamConfig,
+ transmitter: Arc<tokio::sync::broadcast::Sender<Vec<f32>>>,
+ stream_control: mpsc::Sender<StreamControl>,
+ stream_thread: Option<Arc<tokio::sync::Mutex<Option<thread::JoinHandle<()>>>>>,
+}
+
+enum StreamControl {
+ Stop(oneshot::Sender<()>),
+}
+
+impl AudioStream {
+ pub async fn from_device(
+ device: Arc<AudioDevice>,
+ is_running: Arc<AtomicBool>,
+ ) -> Result<Self> {
+ let (tx, _) = broadcast::channel::<Vec<f32>>(1000);
+ let tx_clone = tx.clone();
+ let (cpal_audio_device, config) = get_device_and_config(&device).await?;
+ let channels = config.channels();
+
+ let is_running_weak_2 = Arc::downgrade(&is_running);
+ let device_clone = device.clone();
+ let config_clone = config.clone();
+ let (stream_control_tx, stream_control_rx) = mpsc::channel();
+
+ let stream_thread = Arc::new(tokio::sync::Mutex::new(Some(thread::spawn(move || {
+ let device = device_clone;
+ let config = config_clone;
+ let error_callback = move |err: StreamError| {
+ error!("an error occurred on the audio stream: {}", err);
+ if err.to_string().contains("device is no longer valid") {
+ warn!("audio device disconnected. stopping recording.");
+ if let Some(arc) = is_running_weak_2.upgrade() {
+ arc.store(false, Ordering::Relaxed);
+ }
+ }
+ };
+
+ let stream = match config.sample_format() {
+ cpal::SampleFormat::F32 => cpal_audio_device
+ .build_input_stream(
+ &config.into(),
+ move |data: &[f32], _: &_| {
+ let mono = audio_to_mono(data, channels);
+ let _ = tx.send(mono);
+ },
+ error_callback,
+ None,
+ )
+ .expect("Failed to build input stream"),
+ cpal::SampleFormat::I16 => cpal_audio_device
+ .build_input_stream(
+ &config.into(),
+ move |data: &[i16], _: &_| {
+ let mono = audio_to_mono(bytemuck::cast_slice(data), channels);
+ let _ = tx.send(mono);
+ },
+ error_callback,
+ None,
+ )
+ .expect("Failed to build input stream"),
+ cpal::SampleFormat::I32 => cpal_audio_device
+ .build_input_stream(
+ &config.into(),
+ move |data: &[i32], _: &_| {
+ let mono = audio_to_mono(bytemuck::cast_slice(data), channels);
+ let _ = tx.send(mono);
+ },
+ error_callback,
+ None,
+ )
+ .expect("Failed to build input stream"),
+ cpal::SampleFormat::I8 => cpal_audio_device
+ .build_input_stream(
+ &config.into(),
+ move |data: &[i8], _: &_| {
+ let mono = audio_to_mono(bytemuck::cast_slice(data), channels);
+ let _ = tx.send(mono);
+ },
+ error_callback,
+ None,
+ )
+ .expect("Failed to build input stream"),
+ _ => {
+ error!("unsupported sample format: {}", config.sample_format());
+ return;
+ }
+ };
+
+ if let Err(e) = stream.play() {
+ error!("failed to play stream for {}: {}", device.to_string(), e);
+ }
+
+ if let Ok(StreamControl::Stop(response)) = stream_control_rx.recv() {
+ info!("stopped recording audio stream");
+ stream.pause().ok();
+ drop(stream);
+ response.send(()).ok();
+ }
+ }))));
+
+ Ok(AudioStream {
+ device,
+ device_config: config,
+ transmitter: Arc::new(tx_clone),
+ stream_control: stream_control_tx,
+ stream_thread: Some(stream_thread),
+ })
+ }
+
+ pub async fn subscribe(&self) -> broadcast::Receiver<Vec<f32>> {
+ self.transmitter.subscribe()
+ }
+
+ pub async fn stop(mut self) -> Result<()> {
+ let (tx, rx) = oneshot::channel();
+ self.stream_control.send(StreamControl::Stop(tx))?;
+ rx.await?;
+
+ if let Some(thread_arc) = self.stream_thread.take() {
+ let thread_handle = tokio::task::spawn_blocking(move || {
+ let mut thread_guard = thread_arc.blocking_lock();
+ if let Some(join_handle) = thread_guard.take() {
+ join_handle
+ .join()
+ .map_err(|_| anyhow!("failed to join stream thread"))
+ } else {
+ Ok(())
+ }
+ });
+
+ thread_handle.await??;
+ }
+
+ Ok(())
+ }
+}
diff --git a/screenpipe-audio/src/lib.rs b/screenpipe-audio/src/lib.rs
index 25d93b8ff..ef8d2a0d5 100644
--- a/screenpipe-audio/src/lib.rs
+++ b/screenpipe-audio/src/lib.rs
@@ -10,8 +10,8 @@ pub mod whisper;
pub use core::{
default_input_device, default_output_device, list_audio_devices, parse_audio_device,
- record_and_transcribe, trigger_audio_permission, AudioDevice, AudioTranscriptionEngine,
- DeviceControl, DeviceType,
+ record_and_transcribe, trigger_audio_permission, AudioDevice, AudioStream,
+ AudioTranscriptionEngine, DeviceControl, DeviceType,
};
pub use encode::encode_single_audio;
pub use pcm_decode::pcm_decode;
diff --git a/screenpipe-audio/tests/core_tests.rs b/screenpipe-audio/tests/core_tests.rs
index d50f962ea..25e49fe10 100644
--- a/screenpipe-audio/tests/core_tests.rs
+++ b/screenpipe-audio/tests/core_tests.rs
@@ -6,7 +6,8 @@ mod tests {
use screenpipe_audio::vad_engine::{SileroVad, VadEngine, VadEngineEnum, VadSensitivity};
use screenpipe_audio::whisper::WhisperModel;
use screenpipe_audio::{
- default_output_device, list_audio_devices, pcm_decode, AudioInput, AudioTranscriptionEngine,
+ default_output_device, list_audio_devices, pcm_decode, AudioInput, AudioStream,
+ AudioTranscriptionEngine,
};
use screenpipe_audio::{parse_audio_device, record_and_transcribe};
use screenpipe_core::Language;
@@ -55,11 +56,17 @@ mod tests {
let output_path = PathBuf::from(format!("test_output_{}.mp4", time));
let (sender, receiver) = crossbeam::channel::bounded(100);
let is_running = Arc::new(AtomicBool::new(true));
+ let is_running_clone = Arc::clone(&is_running);
+
+ let audio_stream = AudioStream::from_device(device_spec, is_running_clone)
+ .await
+ .unwrap();
// Act
let start_time = Instant::now();
println!("Starting record_and_transcribe");
- let result = record_and_transcribe(device_spec, duration, sender, is_running).await;
+ let result =
+ record_and_transcribe(Arc::new(audio_stream), duration, sender, is_running).await;
println!("record_and_transcribe completed");
let elapsed_time = start_time.elapsed();
@@ -106,6 +113,10 @@ mod tests {
let is_running = Arc::new(AtomicBool::new(true));
let is_running_clone = Arc::clone(&is_running);
+ let audio_stream = AudioStream::from_device(device_spec, is_running_clone.clone())
+ .await
+ .unwrap();
+
// interrupt in 10 seconds
tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(10)).await;
@@ -115,7 +126,7 @@ mod tests {
// Act
let start_time = Instant::now();
- record_and_transcribe(device_spec, duration, sender, is_running)
+ record_and_transcribe(Arc::new(audio_stream), duration, sender, is_running)
.await
.unwrap();
@@ -211,8 +222,12 @@ mod tests {
let recording_thread = tokio::spawn(async move {
let device_spec = Arc::clone(&device_spec);
let whisper_sender = whisper_sender.clone();
+ let audio_stream = AudioStream::from_device(device_spec, is_running.clone())
+ .await
+ .unwrap();
+
record_and_transcribe(
- device_spec,
+ Arc::new(audio_stream),
Duration::from_secs(15),
whisper_sender,
is_running,
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index d9fda0bed..24558f43a 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -5,6 +5,7 @@ use crossbeam::queue::SegQueue;
use futures::future::join_all;
use log::{debug, error, info, warn};
use screenpipe_audio::vad_engine::VadSensitivity;
+use screenpipe_audio::AudioStream;
use screenpipe_audio::{
create_whisper_channel, record_and_transcribe, vad_engine::VadEngineEnum, AudioDevice,
AudioInput, AudioTranscriptionEngine, DeviceControl, TranscriptionResult,
@@ -46,34 +47,6 @@ pub async fn start_continuous_recording(
vad_sensitivity: CliVadSensitivity,
languages: Vec<Language>,
) -> Result<()> {
- let (whisper_sender, whisper_receiver, whisper_shutdown_flag) = if audio_disabled {
- // Create a dummy channel if no audio devices are available, e.g. audio disabled
- let (input_sender, _): (
- crossbeam::channel::Sender<AudioInput>,
- crossbeam::channel::Receiver<AudioInput>,
- ) = crossbeam::channel::bounded(100);
- let (_, output_receiver): (
- crossbeam::channel::Sender<TranscriptionResult>,
- crossbeam::channel::Receiver<TranscriptionResult>,
- ) = crossbeam::channel::bounded(100);
- (
- input_sender,
- output_receiver,
- Arc::new(AtomicBool::new(false)),
- )
- } else {
- create_whisper_channel(
- audio_transcription_engine.clone(),
- VadEngineEnum::from(vad_engine),
- deepgram_api_key,
- &PathBuf::from(output_path.as_ref()),
- VadSensitivity::from(vad_sensitivity),
- languages.clone(),
- )
- .await?
- };
- let whisper_sender_clone = whisper_sender.clone();
- let db_manager_audio = Arc::clone(&db);
// Initialize friend wearable loop
if let Some(uid) = &friend_wearable_uid {
tokio::spawn(initialize_friend_wearable_loop(
@@ -125,6 +98,35 @@ pub async fn start_continuous_recording(
})]
};
+ let (whisper_sender, whisper_receiver, whisper_shutdown_flag) = if audio_disabled {
+ // Create a dummy channel if no audio devices are available, e.g. audio disabled
+ let (input_sender, _): (
+ crossbeam::channel::Sender<AudioInput>,
+ crossbeam::channel::Receiver<AudioInput>,
+ ) = crossbeam::channel::bounded(100);
+ let (_, output_receiver): (
+ crossbeam::channel::Sender<TranscriptionResult>,
+ crossbeam::channel::Receiver<TranscriptionResult>,
+ ) = crossbeam::channel::bounded(100);
+ (
+ input_sender,
+ output_receiver,
+ Arc::new(AtomicBool::new(false)),
+ )
+ } else {
+ create_whisper_channel(
+ audio_transcription_engine.clone(),
+ VadEngineEnum::from(vad_engine),
+ deepgram_api_key,
+ &PathBuf::from(output_path.as_ref()),
+ VadSensitivity::from(vad_sensitivity),
+ languages.clone(),
+ )
+ .await?
+ };
+ let whisper_sender_clone = whisper_sender.clone();
+ let db_manager_audio = Arc::clone(&db);
+
let audio_task = if !audio_disabled {
audio_handle.spawn(async move {
record_audio(
@@ -292,77 +294,45 @@ async fn record_audio(
let handle = tokio::spawn(async move {
let audio_device_clone = Arc::clone(&audio_device);
- let error = Arc::new(AtomicBool::new(false));
+ // let error = Arc::new(AtomicBool::new(false));
debug!(
"Starting audio capture thread for device: {}",
&audio_device
);
- let error_clone = Arc::clone(&error);
- let mut iteration = 0;
- loop {
- let device_control_clone = Arc::clone(&device_control);
- let whisper_sender_clone = whisper_sender_clone.clone();
- let error_clone = Arc::clone(&error_clone);
- if error_clone.load(Ordering::Relaxed) {
- break;
+ let audio_stream = match AudioStream::from_device(
+ audio_device_clone.clone(),
+ Arc::new(AtomicBool::new(device_control.clone().is_running)),
+ )
+ .await
+ {
+ Ok(stream) => stream,
+ Err(e) => {
+ error!("Failed to create audio stream: {}", e);
+ return;
}
- let audio_device = Arc::clone(&audio_device_clone);
- iteration += 1;
- tokio::spawn(async move {
- debug!(
- "Starting iteration {} for device {}",
- iteration, audio_device
- );
-
- // let error_clone = Arc::clone(&error_clone);
- // let whisper_sender_clone_2 = whisper_sender_clone.clone();
- let audio_device_clone = audio_device.clone();
- // let audio_device_clone_2 = audio_device.clone();
-
- debug!(
- "Starting record_and_transcribe for device {} (iteration {})",
- audio_device_clone, iteration
- );
- let result = record_and_transcribe(
- audio_device,
- // audio_device_clone,
- chunk_duration,
- whisper_sender_clone.clone(),
- // whisper_sender_clone_2.clone(),
- Arc::new(AtomicBool::new(device_control_clone.is_running)),
- )
- .await;
- info!(
- "Finished record_and_transcribe for device {} (iteration {})",
- audio_device_clone, iteration
- );
-
- match result {
- Ok(file_path) => {
- info!(
- "Recording complete for device {} (iteration {}): {:?}",
- audio_device_clone, iteration, file_path
- );
- }
- Err(e) => {
- error!(
- "Error in record_and_transcribe for device {} (iteration {}): {}, stopping thread",
- audio_device_clone, iteration, e
- );
- error_clone.store(true, Ordering::Relaxed);
- }
- }
- info!(
- "Finished iteration {} for device {}",
- iteration, &audio_device_clone
- );
- });
+ };
+
+ let audio_stream = Arc::new(audio_stream);
+ let device_control_clone = Arc::clone(&device_control);
+ let whisper_sender_clone = whisper_sender_clone.clone();
+ let audio_device = Arc::clone(&audio_device_clone);
+ let record_handle = tokio::spawn(async move {
+ let _ = record_and_transcribe(
+ audio_stream,
+ chunk_duration,
+ whisper_sender_clone.clone(),
+ Arc::new(AtomicBool::new(device_control_clone.is_running)),
+ )
+ .await;
+ });
- tokio::time::sleep(chunk_duration - OVERLAP_DURATION).await;
- }
+ // let live_transcription_handle = tokio::spawn(async move {
+ // let _ = live_transcription(audio_stream, whisper_sender_clone.clone()).await;
+ // });
- info!("Exiting audio capture thread for device: {}", &audio_device);
+ record_handle.await.unwrap();
+ info!("exiting audio capture thread for device: {}", &audio_device);
});
handles.insert(device_id, handle);