瀏覽代碼

Add volume command

Frans Bergman 2 年之前
父節點
當前提交
519d616555
共有 2 個文件被更改,包括 36 次插入0 次删除
  1. 19 0
      src/audio/audio.rs
  2. 17 0
      src/audio/audio_state.rs

+ 19 - 0
src/audio/audio.rs

@@ -25,6 +25,7 @@ use crate::util::{message_react, send_embed};
     pause,
     resume,
     change_loop,
+    volume,
     shuffle,
     clear,
     queue
@@ -268,6 +269,24 @@ async fn change_loop(ctx: &Context, msg: &Message) -> CommandResult {
     Ok(())
 }
 
+#[command]
+#[aliases("vol")]
+async fn volume(ctx: &Context, msg: &Message, args: Args) -> CommandResult {
+    let audio_state = get_audio_state(ctx, msg).await;
+    let audio_state = match audio_state {
+        Some(audio_state) => audio_state,
+        None => return Ok(()),
+    };
+
+    let volume: u8 = args.rest().parse()?;
+
+    match AudioState::set_volume(audio_state, volume.into()).await {
+        Ok(()) => message_react(ctx, msg, "🎶").await,
+        Err(why) => send_embed(ctx, msg, &format!("Error: {}", why)).await,
+    };
+    Ok(())
+}
+
 #[command]
 async fn queue(ctx: &Context, msg: &Message) -> CommandResult {
     let audio_state = get_audio_state(ctx, msg).await;

+ 17 - 0
src/audio/audio_state.rs

@@ -23,6 +23,7 @@ pub struct AudioState {
     current_song: Mutex<Option<Song>>,
     track_handle: Mutex<Option<TrackHandle>>,
     is_looping: Mutex<bool>,
+    volume: Mutex<f32>,
 
     channel_id: Mutex<ChannelId>,
     http: Mutex<Arc<Http>>,
@@ -36,6 +37,7 @@ impl AudioState {
             current_song: Mutex::new(None),
             track_handle: Mutex::new(None),
             is_looping: Mutex::new(false),
+            volume: Mutex::new(1.0),
 
             channel_id: Mutex::new(msg.channel_id),
             http: Mutex::new(ctx.http.clone()),
@@ -101,8 +103,12 @@ impl AudioState {
         let source = input::Input::float_pcm(true, reader);
 
         let mut handler = audio_state.handler.lock().await;
+        let volume = audio_state.volume.lock().await;
 
         let handle = handler.play_source(source);
+        if let Err(e) = handle.set_volume(*volume) {
+            println!("{}", e);
+        }
 
         if let Err(why) = handle.add_event(
             Event::Track(TrackEvent::End),
@@ -178,6 +184,17 @@ impl AudioState {
         Ok(*is_looping)
     }
 
+    pub async fn set_volume(audio_state: Arc<AudioState>, new_volume: f32) -> Result<(), String> {
+        let mut track_handle = audio_state.track_handle.lock().await;
+        let mut volume = audio_state.volume.lock().await;
+
+        *volume = new_volume / 100.0;
+
+        track_handle.as_mut().map(move |handle| handle.set_volume(*volume));
+
+        Ok(())
+    }
+
     pub async fn get_string(audio_state: Arc<AudioState>) -> String {
         let current_song = audio_state.current_song.lock().await;
         let current_song = match &*current_song {