Skip to content

Commit

Permalink
Fix lyric update
Browse files Browse the repository at this point in the history
  • Loading branch information
HeHang0 committed Jan 11, 2024
1 parent 3b5c428 commit 7d22154
Show file tree
Hide file tree
Showing 17 changed files with 105 additions and 40 deletions.
1 change: 1 addition & 0 deletions .github/workflows/web.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ jobs:
- name: Build
run: |
powershell
node web\scripts\version.js
Remove-Item windows\logo.ico -Force -ErrorAction SilentlyContinue
Remove-Item web\public\logo.png -Force -ErrorAction SilentlyContinue
Remove-Item web\public\logo-circle.png -Force -ErrorAction SilentlyContinue
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ private void onMethodCall(MethodCall call, MethodChannel.Result result){

private void updateMetaData(boolean playing, Integer position){
if(position == null) return;
if(!playing && isServiceNotRunning(mBinding.getApplicationContext(), LyricService.class)) return;
if(!playing && isServiceNotRunning(mBinding.getApplicationContext(), NotificationService.class)) return;
Intent intent = new Intent(mBinding.getApplicationContext(), NotificationService.class);
intent.putExtra("playing", playing);
intent.putExtra("position", position.intValue());
Expand All @@ -122,7 +122,7 @@ private void updateMetaData(boolean playing, Integer position){
private void updateMetaData(
String title, String artist, String album, String artwork,
boolean playing, boolean lover, Integer position, Integer duration) {
if(!playing && isServiceNotRunning(mBinding.getApplicationContext(), LyricService.class)) return;
if(!playing && isServiceNotRunning(mBinding.getApplicationContext(), NotificationService.class)) return;
Intent intent = new Intent(mBinding.getApplicationContext(), NotificationService.class);
intent.putExtra("playing", playing);
intent.putExtra("lover", lover);
Expand Down
2 changes: 1 addition & 1 deletion mobile/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1
version: 2.1.0

environment:
sdk: '>=3.2.3 <4.0.0'
Expand Down
2 changes: 1 addition & 1 deletion web/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "musiche",
"version": "1.0.0",
"version": "2.1.0",
"description": "A Swiss Army knife for developers.",
"main": "index.js",
"repository": "https://github.com/HeHang0/DevToys.git",
Expand Down
2 changes: 1 addition & 1 deletion web/scripts/fix.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ function transformIndexHtmlHandler(html: string) {
const manifestLink = document.querySelector('link[rel="manifest"]');
if(manifestLink) manifestLink.href = location.origin + routerPrefix + '/manifest.json';
${workerJS}
${indexJS}${indexCSS}
${indexCSS}${indexJS}
document.getElementById('musiche-script-fix').remove();
</script>
</head>`
Expand Down
23 changes: 23 additions & 0 deletions web/scripts/version.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const fs = require('fs');
const path = require('path');
const rootDir = path.join(__dirname, '..', '..');
const packagePath = path.join(rootDir, 'web', 'package.json');
const manifestPath = path.join(rootDir, 'web', 'public', 'manifest.json');
const packageJson = require(packagePath);
const manifestJson = require(manifestPath);
manifestJson.version = packageJson.version;
fs.writeFileSync(manifestPath, JSON.stringify(manifestJson, null, 2));
const windowsVersionPath = path.join(rootDir, 'windows', 'Musiche.csproj');
let windowsSlnText = fs.readFileSync(windowsVersionPath, 'utf-8');
windowsSlnText = windowsSlnText.replace(
/\<Version\>[\d\.]+\<\/Version\>/,
`<Version>${packageJson.version}</Version>`
);
fs.writeFileSync(windowsVersionPath, windowsSlnText);
const mobileVersionPath = path.join(rootDir, 'mobile', 'pubspec.yaml');
let mobileSpecText = fs.readFileSync(mobileVersionPath, 'utf-8');
mobileSpecText = mobileSpecText.replace(
/version: [d.]+/,
`version: ${packageJson.version}`
);
fs.writeFileSync(mobileVersionPath, mobileSpecText);
2 changes: 2 additions & 0 deletions web/src/components/SideMenu.vue
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useRoute, useRouter } from 'vue-router';
import { usePlayStore } from '../stores/play';
import { LogoImage, LogoCircleImage } from '../utils/logo';
import { useSettingStore } from '../stores/setting';
import { getServiceWorkerRegistration } from '../sw/register';
const { options, push } = useRouter();
const route = useRoute();
const play = usePlayStore();
Expand All @@ -29,6 +30,7 @@ function createMyPlaylists() {
createPlaylistShow.value = false;
}
function toHome() {
getServiceWorkerRegistration()?.update();
push('/');
}
</script>
Expand Down
1 change: 1 addition & 0 deletions web/src/components/WindowControls.vue
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ function prepareClose() {
)
})
.then(close)
.catch(() => {})
.finally(() => {
closing = false;
});
Expand Down
6 changes: 3 additions & 3 deletions web/src/stores/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ export class MusicConnection {
this.wsClose.bind(this),
this.autoAppThemeChange.bind(this)
);
if (interval) {
setInterval(this.sendWsStatus.bind(this), 500);
}
// if (interval) {
// setInterval(this.sendWsStatus.bind(this), 500);
// }
if (this.setting.pageValue.savePlayProgress) {
try {
const progress = parseInt(
Expand Down
2 changes: 2 additions & 0 deletions web/src/utils/lyric.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ export class LyricManager {
}

public updateLyric(music: Music) {
console.log('updateLyric', music);
const remoteId = `${music.type}${music.id}`;
if (
(this.parsed || this.parsing) &&
Expand Down Expand Up @@ -144,6 +145,7 @@ export class LyricManager {
cancel?: boolean,
music?: Music
) {
console.log('subscribeLyricLine', callback, cancel);
if (!callback) return;
const index = this.lyricLineChanges.indexOf(callback);
if (!cancel && index < 0) {
Expand Down
7 changes: 5 additions & 2 deletions web/src/views/setting.vue
Original file line number Diff line number Diff line change
Expand Up @@ -1199,6 +1199,7 @@ onUnmounted(unWatch);
flex-direction: column;
&-download {
display: flex;
margin-top: 30px;
}
&-update {
cursor: pointer;
Expand All @@ -1207,12 +1208,14 @@ onUnmounted(unWatch);
&-card {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin: 20px 30px 0 0;
text-decoration: none;
text-align: center;
cursor: pointer;
color: -webkit-link;
& + & {
margin-left: 20px;
}
&:hover {
p {
text-decoration: underline;
Expand Down
37 changes: 29 additions & 8 deletions windows/Audio/MediaMetaManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
namespace Musiche.Audio
{
public delegate void AudioStatusChangedEventHandler(object sender, string message);
public class MediaMetaManager
public class MediaMetaManager: IDisposable
{
private readonly Dispatcher _dispatcher;
public Dispatcher Dispatcher => _dispatcher;
Expand All @@ -23,7 +23,13 @@ public class MediaMetaManager
public MediaMetaManager()
{
_dispatcher = Dispatcher.CurrentDispatcher;
}
#if NETFRAMEWORK
MediaPlayer _mediaPlayer = null;
SystemMediaTransportControls _systemMediaTransportControls;
SystemMediaTransportControlsTimelineProperties _systemMediaTimelineProperties;
private void InitMediaPlay()
{
_mediaPlayer = new MediaPlayer();
_systemMediaTransportControls = _mediaPlayer.SystemMediaTransportControls;
_mediaPlayer.CommandManager.IsEnabled = false;
Expand All @@ -37,10 +43,6 @@ public MediaMetaManager()
_systemMediaTransportControls.IsPlayEnabled = true;
_systemMediaTimelineProperties = new SystemMediaTransportControlsTimelineProperties();
}
readonly MediaPlayer _mediaPlayer;
readonly SystemMediaTransportControls _systemMediaTransportControls;
readonly SystemMediaTransportControlsTimelineProperties _systemMediaTimelineProperties;

private void OnMediaTransportControlClick(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
{
string message = string.Empty;
Expand Down Expand Up @@ -71,14 +73,19 @@ private void OnMediaTransportControlClick(SystemMediaTransportControls sender, S
AudioStatusChanged?.Invoke(this, message);
}
}
#else
}
#endif
public void SetMediaMeta(MediaMetadata metadata)
MediaMetadata _metadata = null;
public void SetMediaMeta(MediaMetadata metadata, bool playing)
{
_metadata = metadata;
#if NETFRAMEWORK
try
{
if (_mediaPlayer == null && !playing) return;
if(_mediaPlayer == null)
{
InitMediaPlay();
}
if (_systemMediaTransportControls.DisplayUpdater.Type != MediaPlaybackType.Music)
{
// 如果尚未初始化,则初始化
Expand Down Expand Up @@ -108,6 +115,11 @@ public void SetMediaMeta(MediaMetadata metadata)
public void SetMediaControlPlayState(PlaybackState playbackState)
{
#if NETFRAMEWORK
if (_mediaPlayer == null)
{
InitMediaPlay();
if (_metadata != null) SetMediaMeta(_metadata, playbackState == PlaybackState.Playing);
}
switch (playbackState)
{
//case PlaybackState.Stopped:
Expand All @@ -127,6 +139,7 @@ public void SetMediaControlPlayState(PlaybackState playbackState)
public void UpdateMediaControlTimeline(TimeSpan position, TimeSpan endTime)
{
#if NETFRAMEWORK
if (_mediaPlayer == null) return;
_systemMediaTimelineProperties.StartTime = TimeSpan.Zero;
_systemMediaTimelineProperties.EndTime = endTime;
_systemMediaTimelineProperties.Position = position;
Expand All @@ -139,8 +152,16 @@ public void UpdateMediaControlTimeline(TimeSpan position, TimeSpan endTime)
public void UpdateMediaControlPosition(TimeSpan position)
{
#if NETFRAMEWORK
if (_mediaPlayer == null) return;
_systemMediaTimelineProperties.Position = position;
_systemMediaTransportControls.UpdateTimelineProperties(_systemMediaTimelineProperties);
#endif
}

public void Dispose()
{
#if NETFRAMEWORK
_mediaPlayer?.Dispose();
#endif
}
}
Expand Down
3 changes: 1 addition & 2 deletions windows/LyricWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,7 @@ public void SetLine(string line, double duration=0)
LyricScroll.ScrollToHorizontalOffset(0);
Lyric.Content = line;
lyricTimer?.Stop();
//更新行, 591.4000000000001, 350, 591.4000000000001
System.Diagnostics.Trace.WriteLine($"更新行, {LyricScroll.ExtentWidth}, {LyricScroll.ActualWidth}, {Lyric.ActualWidth}");
System.Diagnostics.Trace.WriteLine($"update lyric line, {LyricScroll.ExtentWidth}, {LyricScroll.ActualWidth}, {Lyric.ActualWidth}");
if (duration > 0 && duration < 60000 && LyricScroll.ExtentWidth > LyricScroll.ActualWidth)
{
scrollStep = (LyricScroll.ExtentWidth - LyricScroll.ActualWidth) / (duration / 33);
Expand Down
34 changes: 18 additions & 16 deletions windows/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,9 @@
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Threading;
using Timer = System.Timers.Timer;

namespace Musiche
{
Expand All @@ -32,7 +30,7 @@ public partial class MainWindow : Window
readonly WebSocketHandler webSocketHandler;
readonly HttpHandler httpHandler;
readonly NotifyIconInfo notifyIcon;
readonly Timer positionTimer;
readonly DispatcherTimer positionTimer;
Stream logStream = null;
Hotkey.Hotkey hotkey = null;
LyricWindow lyricWindow;
Expand All @@ -56,14 +54,12 @@ public MainWindow()
notifyIcon = new NotifyIconInfo(webSocketHandler, ShowApp, ExitApp);
TaskbarItemInfo = taskbarInfo.TaskbarItemInfo;
AppDomain.CurrentDomain.UnhandledException += UnhandledException;
positionTimer = new DispatcherTimer();
positionTimer.Interval = TimeSpan.FromMilliseconds(500);
positionTimer.Tick += UpdateAudioPosition;
positionTimer.Stop();
if(MediaMetaManager.Supported)
{
positionTimer = new Timer();
positionTimer.Interval = 1000;
positionTimer.AutoReset = true;
positionTimer.Enabled = true;
positionTimer.Elapsed += UpdateAudioPosition;
positionTimer.Stop();
mediaMetaManager.AudioStatusChanged += OnAudioStatusChanged;
}
InitNamedPipeServerStream();
Expand All @@ -87,9 +83,13 @@ private async void InitNamedPipeServerStream()
InitNamedPipeServerStream();
}

private void UpdateAudioPosition(object sender, ElapsedEventArgs e)
private void UpdateAudioPosition(object sender, EventArgs e)
{
mediaMetaManager.UpdateMediaControlPosition(audioPlay.CurrentTimeSpan);
_ = webSocketHandler.SendStatus();
if (MediaMetaManager.Supported)
{
mediaMetaManager.UpdateMediaControlPosition(audioPlay.CurrentTimeSpan);
}
}

private void UnhandledException(object sender, UnhandledExceptionEventArgs e)
Expand All @@ -104,14 +104,14 @@ private void AudioPlay_PlatStateChanged(object sender, NAudio.Wave.PlaybackState
notifyIcon?.AudioPlayStateChanged(playing);
taskbarInfo?.AudioPlayStateChanged(playing);
lyricWindow?.AudioPlayStateChanged(playing);
if(MediaMetaManager.Supported)
{
if (playing) positionTimer?.Start();
else positionTimer?.Stop();
}
if (playing) positionTimer?.Start();
else positionTimer?.Stop();
if(state == NAudio.Wave.PlaybackState.Stopped)
{
webSocketHandler.SendMessage("{\"type\": \"next\",\"data\": \"true\"}");
}else
{
UpdateAudioPosition(this, null);
}
}

Expand Down Expand Up @@ -156,6 +156,7 @@ private void MainWindow_Closing(object sender, System.ComponentModel.CancelEvent
{
webSocketHandler.SendMessage("{\"type\": \"close\"}");
webview2?.SaveConfig();
e.Cancel = true;
}

private async void WebServer_ClientConnected(object sender, System.Net.HttpListenerContext context)
Expand Down Expand Up @@ -272,6 +273,7 @@ public void ExitApp(object sender, EventArgs e)
webview2?.SaveConfig();
webview2?.webview2?.Stop();
webview2?.webview2?.Dispose();
mediaMetaManager?.Dispose();
Application.Current.Shutdown();
}

Expand Down
2 changes: 1 addition & 1 deletion windows/Musiche.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
<RepositoryType>git</RepositoryType>
<Product>Musiche</Product>
<Authors>HeHang</Authors>
<Version>2.0.0</Version>
<Version>2.1.0</Version>
<IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract>
</PropertyGroup>

Expand Down
2 changes: 1 addition & 1 deletion windows/Server/HttpHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public async Task SetMedia(HttpListenerContext ctx)
MediaMetadata data = JsonConvert.DeserializeObject<MediaMetadata>(ctx.Request.DataAsString());
_mediaMetaManager.Dispatcher.Invoke(() =>
{
_mediaMetaManager.SetMediaMeta(data);
_mediaMetaManager.SetMediaMeta(data, _audioPlay.Playing);
});
}catch (Exception) { }
await SendString(ctx, "");
Expand Down
Loading

0 comments on commit 7d22154

Please sign in to comment.