Skip to content

Commit

Permalink
Audio fade in, timing exit, local music
Browse files Browse the repository at this point in the history
  • Loading branch information
HeHang0 committed Nov 3, 2023
1 parent b094349 commit 32a5ba3
Show file tree
Hide file tree
Showing 23 changed files with 303 additions and 95 deletions.
49 changes: 46 additions & 3 deletions windows/Audio/AudioPlay.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,37 @@ namespace Musiche.Audio
public delegate void PlatStateChangedEventHandler(object sender, PlaybackState state);
public class AudioPlay
{
MediaFoundationReader mediaFoundationReader = null;
AudioFileReader mediaFoundationReader = null;
WaveOut wasapiOut = null;
public event PlatStateChangedEventHandler PlatStateChanged;
public Dispatcher Dispatcher;
readonly DispatcherTimer fadeInTimer;
float fadeInVolume = 0;
bool fadeIn = false;
public AudioPlay()
{
Dispatcher = Dispatcher.CurrentDispatcher;
fadeInTimer = new DispatcherTimer();
fadeInTimer.Interval = TimeSpan.FromMilliseconds(100);
fadeInTimer.Tick += OnFadeInTimerTick;
wasapiOut = new WaveOut();
}

private void OnFadeInTimerTick(object sender, EventArgs e)
{
if (fadeInVolume > 0 && fadeInVolume > wasapiOut.Volume && fadeInVolume <= 1)
{
wasapiOut.Volume = (float)Math.Min(fadeInVolume, wasapiOut.Volume + 0.1);
Logger.Logger.Debug("设置淡入声音", wasapiOut.Volume);
}
else
{
fadeInVolume = 0;
(sender as DispatcherTimer).Stop();
Logger.Logger.Debug("结束淡入声音", fadeInVolume);
}
}

private void WasapiOut_PlaybackStopped(object sender, StoppedEventArgs e)
{
PlatStateChanged?.Invoke(this, PlaybackState.Stopped);
Expand All @@ -38,11 +59,11 @@ public void Play(string url)
wasapiOut?.Dispose();
try
{
mediaFoundationReader = new MediaFoundationReader(url);
mediaFoundationReader = new AudioFileReader(url);
wasapiOut = new WaveOut();
Volume = _volume;
wasapiOut.PlaybackStopped += WasapiOut_PlaybackStopped;
wasapiOut.Init(mediaFoundationReader);
RunFadeIn();
wasapiOut?.Play();
if (_progress > 0)
{
Expand All @@ -55,15 +76,36 @@ public void Play(string url)
PlatStateChanged?.Invoke(this, wasapiOut?.PlaybackState ?? PlaybackState.Stopped);
}

private void RunFadeIn()
{
if (fadeIn)
{
fadeInVolume = _volume * 1.0f / 100;
wasapiOut.Volume = 0;
fadeInTimer.Start();
Logger.Logger.Debug("开始淡入声音", fadeInVolume);
}
else
{
Volume = _volume;
}
}

public void Play()
{
if (mediaFoundationReader != null)
{
RunFadeIn();
wasapiOut?.Play();
PlatStateChanged?.Invoke(this, wasapiOut?.PlaybackState ?? PlaybackState.Stopped);
}
}

public void SetFadeIn(bool fadeIn)
{
this.fadeIn = fadeIn;
}

public void Pause()
{
if (mediaFoundationReader == null) return;
Expand Down Expand Up @@ -108,6 +150,7 @@ public int Volume
{
get
{
if (fadeInVolume > 0) return (int)(fadeInVolume * 100);
return _volume;
}
set
Expand Down
5 changes: 1 addition & 4 deletions windows/Hotkey/Hotkey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,7 @@
using NHotkey.Wpf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
Expand All @@ -33,7 +30,7 @@ public string Register(ShortcutKey shortcutKey)
return registerMedia();
}
ShortcutType shortcutType = shortcutKey.ParseType();
if(shortcutType == ShortcutType.None) return "热键注册类型不能为空";
if (shortcutType == ShortcutType.None) return "热键注册类型不能为空";
ModifierKeys modifierKeys = shortcutKey.ParseModifierKeys();
Key key = shortcutKey.ParseKey();
if (modifierKeys == ModifierKeys.None) return "修饰键不能为空";
Expand Down
3 changes: 1 addition & 2 deletions windows/Hotkey/ShortcutKey.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using NHotkey;
using NHotkey.Wpf;
using System;
using System.Linq;
using System.Windows.Input;
Expand All @@ -22,7 +21,7 @@ public ShortcutType ParseType()

public static ShortcutType ParseType(string typeString)
{
if(string.IsNullOrEmpty(typeString)) return ShortcutType.None;
if (string.IsNullOrEmpty(typeString)) return ShortcutType.None;
typeString = typeString.First().ToString().ToUpper() + typeString.Substring(1);
if (Enum.TryParse(typeString, out ShortcutType shortcutType))
{
Expand Down
8 changes: 1 addition & 7 deletions windows/Hotkey/ShortcutType.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,3 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Musiche.Hotkey
namespace Musiche.Hotkey
{
}
6 changes: 2 additions & 4 deletions windows/Logger/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Threading;

namespace Musiche.Logger
Expand All @@ -16,8 +14,8 @@ enum LoggerType
Error, Warning, Info, Debug
}

private static HashSet<Stream> streams = new HashSet<Stream>();
private static Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
private static readonly HashSet<Stream> streams = new HashSet<Stream>();
private static readonly Dispatcher dispatcher = Dispatcher.CurrentDispatcher;

public static void Error(params object[] message)
{
Expand Down
3 changes: 2 additions & 1 deletion windows/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Musiche"
xmlns:local="clr-namespace:Musiche" xmlns:webview2="clr-namespace:Musiche.Webview2"
mc:Ignorable="d" WindowStartupLocation="CenterScreen"
Title="" Height="750" Width="1055" MinHeight="750" MinWidth="1055">
<WindowChrome.WindowChrome>
<WindowChrome CaptionHeight="20" ResizeBorderThickness="4" CornerRadius="8" GlassFrameThickness="-1" UseAeroCaptionButtons="True" />
</WindowChrome.WindowChrome>
<webview2:Webview2Control x:Name="webview2"></webview2:Webview2Control>
</Window>
57 changes: 51 additions & 6 deletions windows/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@
using Musiche.Server;
using Musiche.Webview2;
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace Musiche
Expand All @@ -15,7 +18,7 @@ namespace Musiche
/// </summary>
public partial class MainWindow : Window
{
readonly Webview2Control webview2;
//readonly Webview2Control webview2;
readonly AudioPlay audioPlay;
readonly WebServer webServer;
readonly WebSocketHandler webSocketHandler;
Expand All @@ -27,20 +30,20 @@ public MainWindow()
{
InitializeComponent();
audioPlay = new AudioPlay();
webview2 = new Webview2Control();
InitWebview2();
WindowState = WindowState.Minimized;
#if DEBUG
webServer = new WebServer(54621);
webview2.Control.Source = new Uri("http://127.0.0.1:54621");
webview2.Control.Source = new Uri("http://127.0.0.1:5173");
string exeDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
logStream = File.Open(Path.Combine(exeDirectory, "log."+DateTime.Now.ToString("yyyy-MM-dd")+".log"), FileMode.Append);
logStream = System.IO.File.Open(Path.Combine(exeDirectory, "log." + DateTime.Now.ToString("yyyy-MM-dd") + ".log"), FileMode.Append);
#else
int port = GetAvailablePort();
webServer = new WebServer(port);
webview2.Control.Source = new Uri("http://localhost:"+port);
#endif
webSocketHandler = new WebSocketHandler(this, audioPlay);
httpHandler = new HttpHandler(this, audioPlay);
InitWebview2();
StateChanged += MainWindow_StateChanged;
Closing += MainWindow_Closing;
SourceInitialized += MainWindow_SourceInitialized;
Expand Down Expand Up @@ -101,7 +104,9 @@ private void InitWebview2()
{
if (Webview2Control.Available)
{
Content = webview2;
//Content = webview2;
//Hide();
webview2.CoreWebView2DOMContentLoaded += Webview2_CoreWebView2DOMContentLoaded;
}
else
{
Expand All @@ -110,6 +115,46 @@ private void InitWebview2()
}
}

private void Webview2_CoreWebView2DOMContentLoaded(object sender, Microsoft.Web.WebView2.Core.CoreWebView2DOMContentLoadedEventArgs e)
{
webview2.CoreWebView2DOMContentLoaded -= Webview2_CoreWebView2DOMContentLoaded;
Left = (SystemParameters.PrimaryScreenWidth / 2) - (ActualWidth / 2);
Top = (SystemParameters.PrimaryScreenHeight / 2) - (ActualHeight / 2);
WindowState = WindowState.Normal;
}

private CancellationTokenSource deleyExitTaskCancel = null;
private bool delayExitShutdown = false;
public void DelayExit(int minute, bool shutdown)
{
delayExitShutdown = shutdown;
deleyExitTaskCancel?.Cancel();
deleyExitTaskCancel?.Dispose();
deleyExitTaskCancel = null;
if (minute > 0)
{
deleyExitTaskCancel = new CancellationTokenSource();
Task.Delay(minute * 60 * 1000, deleyExitTaskCancel.Token).ContinueWith(ExitOnDelay);
}
}

private void ExitOnDelay(Task sender)
{
if (sender.IsCanceled) return;
Dispatcher.Invoke(() =>
{
try
{
if (delayExitShutdown) Process.Start(new ProcessStartInfo("shutdown", "/s /t 30") { UseShellExecute = true });
}
catch (Exception ex)
{
Logger.Logger.Error("Shutdown Error: ", ex);
}
ExitApp(null, null);
});
}

private static int GetAvailablePort()
{
TcpListener listener = new TcpListener(IPAddress.Loopback, 0);
Expand Down
12 changes: 6 additions & 6 deletions windows/NotifyIcon/ModernToolStripRenderer.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
using System.Drawing.Drawing2D;
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using System;
using System.Windows.Forms;

namespace Musiche.NotifyIcon
{
public class ModernToolStripRenderer : ToolStripProfessionalRenderer
{
private Font iconFont;
private System.Drawing.Text.PrivateFontCollection privateFonts;
private readonly Font iconFont;
private readonly System.Drawing.Text.PrivateFontCollection privateFonts;
public ModernToolStripRenderer()
{
int length = Properties.Resources.iconfont.Length;
Expand Down Expand Up @@ -125,7 +125,7 @@ protected override void OnRenderImageMargin(ToolStripRenderEventArgs e)

protected override void OnRenderItemImage(ToolStripItemImageRenderEventArgs e)
{
if(e.Item.Tag != null)
if (e.Item.Tag != null)
{
e.Graphics.DrawString(e.Item.Tag.ToString(), iconFont, new SolidBrush(e.Item.ForeColor), e.ImageRectangle.X + 5, e.ImageRectangle.Y + 5);
}
Expand Down
1 change: 0 additions & 1 deletion windows/NotifyIcon/NotifyIcon.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
Expand Down
7 changes: 3 additions & 4 deletions windows/NotifyIcon/NotifyIconInfo.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Musiche.Audio;
using Musiche.Server;
using Musiche.Server;
using NAudio.Wave;
using System;
using System.Drawing;
Expand Down Expand Up @@ -104,7 +103,7 @@ private void LoopTypeChange(object sender, EventArgs e)
case "顺": loopType = "order"; break;
}
if (menuItem == null) return;
webSocketHandler.SendMessage("{\"type\": \"loop\",\"data\":\""+ loopType + "\"}");
webSocketHandler.SendMessage("{\"type\": \"loop\",\"data\":\"" + loopType + "\"}");
}

public void Dispose()
Expand All @@ -119,7 +118,7 @@ public void SetMusicLoopType(string loopType)
case "single": loopType = "单"; break;
case "random": loopType = "随"; break;
case "order": loopType = "顺"; break;
default : loopType = "环"; break;
default: loopType = "环"; break;
}
loopTypeMenu.Tag = loopType;
loopTypeMenu.Image = new Bitmap(1, 1);
Expand Down
8 changes: 2 additions & 6 deletions windows/Server/FileHandler.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO.Compression;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Compression;

namespace Musiche.Server
{
Expand Down Expand Up @@ -59,7 +55,7 @@ public byte[] GetFile(string filePath)

public string GetMimeType(string filePath)
{
switch(Path.GetExtension(filePath))
switch (Path.GetExtension(filePath))
{
case ".html":
return "text/html";
Expand Down
1 change: 0 additions & 1 deletion windows/Server/Handler.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using Musiche.Audio;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;

namespace Musiche.Server
{
Expand Down
Loading

0 comments on commit 32a5ba3

Please sign in to comment.