system audio capture via wasapi loopback

This commit is contained in:
2026-05-12 01:39:02 +03:00
parent c95e8067c0
commit 63e41297e9
5 changed files with 392 additions and 12 deletions
+77
View File
@@ -0,0 +1,77 @@
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use anyhow::{anyhow, Context, Result};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
pub struct AudioSession {
_stream: cpal::Stream,
pub output_path: PathBuf,
pub sample_rate: u32,
pub channels: u16,
writer: Arc<Mutex<Option<BufWriter<File>>>>,
}
pub fn start(output_path: PathBuf) -> Result<AudioSession> {
let host = cpal::default_host();
let device = host
.default_output_device()
.ok_or_else(|| anyhow!("no default output device for loopback"))?;
let supported = device
.default_output_config()
.context("default output config")?;
let sample_rate = supported.sample_rate().0;
let channels = supported.channels();
let stream_config: cpal::StreamConfig = supported.config();
if let Some(parent) = output_path.parent() {
std::fs::create_dir_all(parent).ok();
}
let file = File::create(&output_path).context("creating audio output file")?;
let writer = Arc::new(Mutex::new(Some(BufWriter::new(file))));
let writer_clone = writer.clone();
let stream = device
.build_input_stream(
&stream_config,
move |data: &[f32], _info: &cpal::InputCallbackInfo| {
if let Ok(mut guard) = writer_clone.lock() {
if let Some(w) = guard.as_mut() {
let bytes: &[u8] = bytemuck_cast(data);
let _ = w.write_all(bytes);
}
}
},
|err| tracing::warn!("audio capture error: {err}"),
None,
)
.context("building input stream")?;
stream.play().context("starting audio stream")?;
Ok(AudioSession {
_stream: stream,
output_path,
sample_rate,
channels,
writer,
})
}
impl AudioSession {
pub fn stop(self) -> Result<PathBuf> {
drop(self._stream);
if let Ok(mut guard) = self.writer.lock() {
if let Some(mut w) = guard.take() {
let _ = w.flush();
}
}
Ok(self.output_path)
}
}
fn bytemuck_cast(data: &[f32]) -> &[u8] {
let len_bytes = std::mem::size_of_val(data);
unsafe { std::slice::from_raw_parts(data.as_ptr() as *const u8, len_bytes) }
}