audio.rs

 1use assets::SoundRegistry;
 2use gpui::{AppContext, AssetSource};
 3use rodio::{OutputStream, OutputStreamHandle};
 4use util::ResultExt;
 5
 6mod assets;
 7
 8pub fn init(source: impl AssetSource, cx: &mut AppContext) {
 9    cx.set_global(SoundRegistry::new(source));
10    cx.set_global(Audio::new());
11}
12
13pub enum Sound {
14    Joined,
15    Leave,
16    Mute,
17    Unmute,
18    StartScreenshare,
19    StopScreenshare,
20}
21
22impl Sound {
23    fn file(&self) -> &'static str {
24        match self {
25            Self::Joined => "joined_call",
26            Self::Leave => "leave_call",
27            Self::Mute => "mute",
28            Self::Unmute => "unmute",
29            Self::StartScreenshare => "start_screenshare",
30            Self::StopScreenshare => "stop_screenshare",
31        }
32    }
33}
34
35pub struct Audio {
36    _output_stream: Option<OutputStream>,
37    output_handle: Option<OutputStreamHandle>,
38}
39
40impl Audio {
41    pub fn new() -> Self {
42        let (_output_stream, output_handle) = OutputStream::try_default().log_err().unzip();
43
44        Self {
45            _output_stream,
46            output_handle,
47        }
48    }
49
50    pub fn play_sound(sound: Sound, cx: &AppContext) {
51        if !cx.has_global::<Self>() {
52            return;
53        }
54
55        let this = cx.global::<Self>();
56
57        let Some(output_handle) = this.output_handle.as_ref() else {
58            return;
59        };
60
61        let Some(source) = SoundRegistry::global(cx).get(sound.file()).log_err() else {
62        return;
63    };
64
65        output_handle.play_raw(source).log_err();
66    }
67}