zed/crates/audio2/src/audio2.rs

82 lines
2 KiB
Rust
Raw Normal View History

2023-10-24 15:15:59 +00:00
use assets::SoundRegistry;
2023-11-01 18:59:49 +00:00
use gpui2::{AppContext, AssetSource};
2023-10-24 15:15:59 +00:00
use rodio::{OutputStream, OutputStreamHandle};
use util::ResultExt;
mod assets;
pub fn init(source: impl AssetSource, cx: &mut AppContext) {
cx.set_global(SoundRegistry::new(source));
2023-11-01 18:59:49 +00:00
cx.set_global(Audio::new());
2023-10-24 15:15:59 +00:00
}
pub enum Sound {
Joined,
Leave,
Mute,
Unmute,
StartScreenshare,
StopScreenshare,
}
impl Sound {
fn file(&self) -> &'static str {
match self {
Self::Joined => "joined_call",
Self::Leave => "leave_call",
Self::Mute => "mute",
Self::Unmute => "unmute",
Self::StartScreenshare => "start_screenshare",
Self::StopScreenshare => "stop_screenshare",
}
}
}
pub struct Audio {
_output_stream: Option<OutputStream>,
output_handle: Option<OutputStreamHandle>,
}
2023-11-01 18:59:49 +00:00
impl Audio {
pub fn new() -> Self {
Self {
_output_stream: None,
output_handle: None,
}
}
2023-10-24 15:15:59 +00:00
fn ensure_output_exists(&mut self) -> Option<&OutputStreamHandle> {
if self.output_handle.is_none() {
let (_output_stream, output_handle) = OutputStream::try_default().log_err().unzip();
self.output_handle = output_handle;
self._output_stream = _output_stream;
}
self.output_handle.as_ref()
}
2023-10-24 15:42:51 +00:00
pub fn play_sound(sound: Sound, cx: &mut AppContext) {
if !cx.has_global::<Self>() {
return;
}
2023-11-01 18:59:49 +00:00
cx.update_global::<Self, _>(|this, cx| {
let output_handle = this.ensure_output_exists()?;
let source = SoundRegistry::global(cx).get(sound.file()).log_err()?;
output_handle.play_raw(source).log_err()?;
Some(())
});
2023-10-24 15:15:59 +00:00
}
2023-11-01 18:59:49 +00:00
pub fn end_call(cx: &mut AppContext) {
2023-10-24 15:42:51 +00:00
if !cx.has_global::<Self>() {
return;
}
2023-11-01 18:59:49 +00:00
cx.update_global::<Self, _>(|this, _| {
this._output_stream.take();
this.output_handle.take();
});
2023-10-24 15:15:59 +00:00
}
}