audio2.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        Self {
43            _output_stream: None,
44            output_handle: None,
45        }
46    }
47
48    fn ensure_output_exists(&mut self) -> Option<&OutputStreamHandle> {
49        if self.output_handle.is_none() {
50            let (_output_stream, output_handle) = OutputStream::try_default().log_err().unzip();
51            self.output_handle = output_handle;
52            self._output_stream = _output_stream;
53        }
54
55        self.output_handle.as_ref()
56    }
57
58    pub fn play_sound(sound: Sound, cx: &mut AppContext) {
59        if !cx.has_global::<Self>() {
60            return;
61        }
62
63        cx.update_global::<Self, _>(|this, cx| {
64            let output_handle = this.ensure_output_exists()?;
65            let source = SoundRegistry::global(cx).get(sound.file()).log_err()?;
66            output_handle.play_raw(source).log_err()?;
67            Some(())
68        });
69    }
70
71    pub fn end_call(cx: &mut AppContext) {
72        if !cx.has_global::<Self>() {
73            return;
74        }
75
76        cx.update_global::<Self, _>(|this, _| {
77            this._output_stream.take();
78            this.output_handle.take();
79        });
80    }
81}