feat: v0.3.0 - 流式播放、本地音乐、下载系统、漫游修复

### 新功能
- 流式播放:边下载边播放,缓冲 64KB 后即刻开始,无需等待完整下载
- 本地音乐页面:支持浏览、播放本地歌曲,横向菜单含「从磁盘删除」
- 下载系统:支持下载歌曲到自定义路径,保存完整元数据(封面/专辑/时长)
- 封面补全:本地音乐缺少封面时自动从网易云 API 获取
- 更新信息:接入 Gitea Releases API,查看最新版更新日志

### 修复
- 修复私人漫游播完一首歌后跳三首的问题(双重触发:audio-ended + startTick)
- 修复全屏漫游抽屉和漫游页面无封面歌曲显示破损图片
- 修复 PlayerBar 无封面歌曲显示破损图片
- 修复下载路径修改后不生效(Rust serde camelCase 映射)
- 修复本地音乐始终只显示默认路径歌曲
- 修复下载完成提示弹出 4 次
- 修复播放网络歌曲时进度条先走但无声音(audio-started 事件同步)

### 优化
- PlayerBar 下载状态:未下载显示下载按钮,下载中显示进度,已下载不显示
- audio.rs 新增 manual_stop 标志防止 stop_audio 触发虚假 audio-ended
- player.ts 新增 waitForAudioStart() 确保 playing 状态与实际播放同步
- 切歌/停止时立即清除 tickInterval 防止重复触发 next()
This commit is contained in:
2026-05-15 02:24:48 +08:00
parent 02f7df4201
commit 718d3ed641
25 changed files with 2123 additions and 216 deletions

45
package-lock.json generated
View File

@ -1,15 +1,19 @@
{ {
"name": "demo", "name": "nekosonic",
"version": "0.1.0", "version": "0.1.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "demo", "name": "nekosonic",
"version": "0.1.0", "version": "0.1.0",
"dependencies": { "dependencies": {
"@tauri-apps/api": "^2", "@tauri-apps/api": "^2",
"@tauri-apps/plugin-dialog": "^2.7.1",
"@tauri-apps/plugin-global-shortcut": "^2.3.1",
"@tauri-apps/plugin-opener": "^2", "@tauri-apps/plugin-opener": "^2",
"@tauri-apps/plugin-process": "^2.3.1",
"@tauri-apps/plugin-updater": "^2.10.1",
"axios": "^1.16.0", "axios": "^1.16.0",
"howler": "^2.2.4", "howler": "^2.2.4",
"pinia": "^3.0.4", "pinia": "^3.0.4",
@ -1485,6 +1489,24 @@
"node": ">= 10" "node": ">= 10"
} }
}, },
"node_modules/@tauri-apps/plugin-dialog": {
"version": "2.7.1",
"resolved": "https://registry.npmmirror.com/@tauri-apps/plugin-dialog/-/plugin-dialog-2.7.1.tgz",
"integrity": "sha512-OK1UBXYt+ojcmxMktzzuyonYIFta8CmAASpX+CA+DTGK24KlHjhYI6x2iOJ/TjZF4N7/ACK1oFmEOjIY9IhzOQ==",
"license": "MIT OR Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.11.0"
}
},
"node_modules/@tauri-apps/plugin-global-shortcut": {
"version": "2.3.1",
"resolved": "https://registry.npmmirror.com/@tauri-apps/plugin-global-shortcut/-/plugin-global-shortcut-2.3.1.tgz",
"integrity": "sha512-vr40W2N6G63dmBPaha1TsBQLLURXG538RQbH5vAm0G/ovVZyXJrmZR1HF1W+WneNloQvwn4dm8xzwpEXRW560g==",
"license": "MIT OR Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.8.0"
}
},
"node_modules/@tauri-apps/plugin-opener": { "node_modules/@tauri-apps/plugin-opener": {
"version": "2.5.4", "version": "2.5.4",
"resolved": "https://registry.npmmirror.com/@tauri-apps/plugin-opener/-/plugin-opener-2.5.4.tgz", "resolved": "https://registry.npmmirror.com/@tauri-apps/plugin-opener/-/plugin-opener-2.5.4.tgz",
@ -1494,6 +1516,24 @@
"@tauri-apps/api": "^2.11.0" "@tauri-apps/api": "^2.11.0"
} }
}, },
"node_modules/@tauri-apps/plugin-process": {
"version": "2.3.1",
"resolved": "https://registry.npmmirror.com/@tauri-apps/plugin-process/-/plugin-process-2.3.1.tgz",
"integrity": "sha512-nCa4fGVaDL/B9ai03VyPOjfAHRHSBz5v6F/ObsB73r/dA3MHHhZtldaDMIc0V/pnUw9ehzr2iEG+XkSEyC0JJA==",
"license": "MIT OR Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.8.0"
}
},
"node_modules/@tauri-apps/plugin-updater": {
"version": "2.10.1",
"resolved": "https://registry.npmmirror.com/@tauri-apps/plugin-updater/-/plugin-updater-2.10.1.tgz",
"integrity": "sha512-NFYMg+tWOZPJdzE/PpFj2qfqwAWwNS3kXrb1tm1gnBJ9mYzZ4WDRrwy8udzWoAnfGCHLuePNLY1WVCNHnh3eRA==",
"license": "MIT OR Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.10.1"
}
},
"node_modules/@types/estree": { "node_modules/@types/estree": {
"version": "1.0.8", "version": "1.0.8",
"resolved": "https://registry.npmmirror.com/@types/estree/-/estree-1.0.8.tgz", "resolved": "https://registry.npmmirror.com/@types/estree/-/estree-1.0.8.tgz",
@ -1507,7 +1547,6 @@
"integrity": "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==", "integrity": "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"undici-types": "~7.19.0" "undici-types": "~7.19.0"
} }

View File

@ -1,7 +1,7 @@
{ {
"name": "nekosonic", "name": "nekosonic",
"private": true, "private": true,
"version": "0.1.0", "version": "0.3.0",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
@ -11,7 +11,11 @@
}, },
"dependencies": { "dependencies": {
"@tauri-apps/api": "^2", "@tauri-apps/api": "^2",
"@tauri-apps/plugin-dialog": "^2.7.1",
"@tauri-apps/plugin-global-shortcut": "^2.3.1",
"@tauri-apps/plugin-opener": "^2", "@tauri-apps/plugin-opener": "^2",
"@tauri-apps/plugin-process": "^2.3.1",
"@tauri-apps/plugin-updater": "^2.10.1",
"axios": "^1.16.0", "axios": "^1.16.0",
"howler": "^2.2.4", "howler": "^2.2.4",
"pinia": "^3.0.4", "pinia": "^3.0.4",

328
src-tauri/Cargo.lock generated
View File

@ -4,9 +4,13 @@ version = 4
[[package]] [[package]]
name = "Nekosonic" name = "Nekosonic"
version = "0.1.0" version = "0.3.0"
dependencies = [ dependencies = [
"base64 0.22.1",
"cpal", "cpal",
"dirs 5.0.1",
"futures-util",
"lofty",
"ncm-api-rs", "ncm-api-rs",
"reqwest 0.12.28", "reqwest 0.12.28",
"rodio", "rodio",
@ -14,7 +18,10 @@ dependencies = [
"serde_json", "serde_json",
"tauri", "tauri",
"tauri-build", "tauri-build",
"tauri-plugin-dialog",
"tauri-plugin-global-shortcut",
"tauri-plugin-opener", "tauri-plugin-opener",
"tauri-plugin-process",
"tauri-plugin-single-instance", "tauri-plugin-single-instance",
"tokio", "tokio",
] ]
@ -859,6 +866,12 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f" checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f"
[[package]]
name = "data-encoding"
version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8"
[[package]] [[package]]
name = "dbus" name = "dbus"
version = "0.9.11" version = "0.9.11"
@ -923,13 +936,34 @@ dependencies = [
"crypto-common", "crypto-common",
] ]
[[package]]
name = "dirs"
version = "5.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225"
dependencies = [
"dirs-sys 0.4.1",
]
[[package]] [[package]]
name = "dirs" name = "dirs"
version = "6.0.0" version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"
dependencies = [ dependencies = [
"dirs-sys", "dirs-sys 0.5.0",
]
[[package]]
name = "dirs-sys"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c"
dependencies = [
"libc",
"option-ext",
"redox_users 0.4.6",
"windows-sys 0.48.0",
] ]
[[package]] [[package]]
@ -940,7 +974,7 @@ checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"
dependencies = [ dependencies = [
"libc", "libc",
"option-ext", "option-ext",
"redox_users", "redox_users 0.5.2",
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
@ -1473,6 +1507,16 @@ dependencies = [
"version_check", "version_check",
] ]
[[package]]
name = "gethostname"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"
dependencies = [
"rustix",
"windows-link 0.2.1",
]
[[package]] [[package]]
name = "getrandom" name = "getrandom"
version = "0.2.17" version = "0.2.17"
@ -1598,6 +1642,24 @@ version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
[[package]]
name = "global-hotkey"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9247516746aa8e53411a0db9b62b0e24efbcf6a76e0ba73e5a91b512ddabed7"
dependencies = [
"crossbeam-channel",
"keyboard-types",
"objc2",
"objc2-app-kit",
"once_cell",
"serde",
"thiserror 2.0.18",
"windows-sys 0.59.0",
"x11rb",
"xkeysym",
]
[[package]] [[package]]
name = "gobject-sys" name = "gobject-sys"
version = "0.18.0" version = "0.18.0"
@ -2310,6 +2372,32 @@ dependencies = [
"scopeguard", "scopeguard",
] ]
[[package]]
name = "lofty"
version = "0.22.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca260c51a9c71f823fbfd2e6fbc8eb2ee09834b98c00763d877ca8bfa85cde3e"
dependencies = [
"byteorder",
"data-encoding",
"flate2",
"lofty_attr",
"log",
"ogg_pager",
"paste",
]
[[package]]
name = "lofty_attr"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed9983e64b2358522f745c1251924e3ab7252d55637e80f6a0a3de642d6a9efc"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]] [[package]]
name = "log" name = "log"
version = "0.4.29" version = "0.4.29"
@ -2723,6 +2811,7 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [ dependencies = [
"bitflags 2.11.1", "bitflags 2.11.1",
"block2", "block2",
"libc",
"objc2", "objc2",
"objc2-core-foundation", "objc2-core-foundation",
] ]
@ -2827,6 +2916,15 @@ dependencies = [
"byteorder", "byteorder",
] ]
[[package]]
name = "ogg_pager"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d6d1ca8364b84e0cf725eed06b1460c44671e6c0fb28765f5262de3ece07fdc"
dependencies = [
"byteorder",
]
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.21.4" version = "1.21.4"
@ -2915,6 +3013,12 @@ dependencies = [
"windows-link 0.2.1", "windows-link 0.2.1",
] ]
[[package]]
name = "paste"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]] [[package]]
name = "pathdiff" name = "pathdiff"
version = "0.2.3" version = "0.2.3"
@ -3307,7 +3411,7 @@ dependencies = [
"once_cell", "once_cell",
"socket2", "socket2",
"tracing", "tracing",
"windows-sys 0.59.0", "windows-sys 0.60.2",
] ]
[[package]] [[package]]
@ -3405,6 +3509,17 @@ dependencies = [
"bitflags 2.11.1", "bitflags 2.11.1",
] ]
[[package]]
name = "redox_users"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43"
dependencies = [
"getrandom 0.2.17",
"libredox",
"thiserror 1.0.69",
]
[[package]] [[package]]
name = "redox_users" name = "redox_users"
version = "0.5.2" version = "0.5.2"
@ -3503,12 +3618,14 @@ dependencies = [
"sync_wrapper", "sync_wrapper",
"tokio", "tokio",
"tokio-rustls", "tokio-rustls",
"tokio-util",
"tower", "tower",
"tower-http", "tower-http",
"tower-service", "tower-service",
"url", "url",
"wasm-bindgen", "wasm-bindgen",
"wasm-bindgen-futures", "wasm-bindgen-futures",
"wasm-streams 0.4.2",
"web-sys", "web-sys",
"webpki-roots", "webpki-roots",
] ]
@ -3543,10 +3660,34 @@ dependencies = [
"url", "url",
"wasm-bindgen", "wasm-bindgen",
"wasm-bindgen-futures", "wasm-bindgen-futures",
"wasm-streams", "wasm-streams 0.5.0",
"web-sys", "web-sys",
] ]
[[package]]
name = "rfd"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a15ad77d9e70a92437d8f74c35d99b4e4691128df018833e99f90bcd36152672"
dependencies = [
"block2",
"dispatch2",
"glib-sys",
"gobject-sys",
"gtk-sys",
"js-sys",
"log",
"objc2",
"objc2-app-kit",
"objc2-core-foundation",
"objc2-foundation",
"raw-window-handle",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"windows-sys 0.60.2",
]
[[package]] [[package]]
name = "ring" name = "ring"
version = "0.17.14" version = "0.17.14"
@ -4290,7 +4431,7 @@ dependencies = [
"anyhow", "anyhow",
"bytes", "bytes",
"cookie", "cookie",
"dirs", "dirs 6.0.0",
"dunce", "dunce",
"embed_plist", "embed_plist",
"getrandom 0.3.4", "getrandom 0.3.4",
@ -4340,7 +4481,7 @@ checksum = "be9aa8c59a894f76c29a002501c589de5eb4987a5913d62a6e0a47f320901988"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"cargo_toml", "cargo_toml",
"dirs", "dirs 6.0.0",
"glob", "glob",
"heck 0.5.0", "heck 0.5.0",
"json-patch", "json-patch",
@ -4410,6 +4551,63 @@ dependencies = [
"walkdir", "walkdir",
] ]
[[package]]
name = "tauri-plugin-dialog"
version = "2.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65981abb771e74e571a38196c3baa11c459379164791eba0e67abc1a5fac9884"
dependencies = [
"log",
"raw-window-handle",
"rfd",
"serde",
"serde_json",
"tauri",
"tauri-plugin",
"tauri-plugin-fs",
"thiserror 2.0.18",
"url",
]
[[package]]
name = "tauri-plugin-fs"
version = "2.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7ecc274121aca0c036a2b42d1cbe83d368d348f54e0bb8a735c2b1548e8f371"
dependencies = [
"anyhow",
"dunce",
"glob",
"log",
"objc2-foundation",
"percent-encoding",
"schemars 0.8.22",
"serde",
"serde_json",
"serde_repr",
"tauri",
"tauri-plugin",
"tauri-utils",
"thiserror 2.0.18",
"toml 1.1.2+spec-1.1.0",
"url",
]
[[package]]
name = "tauri-plugin-global-shortcut"
version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "424af23c7e88d05e4a1a6fc2c7be077912f8c76bd7900fd50aa2b7cbf5a2c405"
dependencies = [
"global-hotkey",
"log",
"serde",
"serde_json",
"tauri",
"tauri-plugin",
"thiserror 2.0.18",
]
[[package]] [[package]]
name = "tauri-plugin-opener" name = "tauri-plugin-opener"
version = "2.5.4" version = "2.5.4"
@ -4432,6 +4630,16 @@ dependencies = [
"zbus", "zbus",
] ]
[[package]]
name = "tauri-plugin-process"
version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d55511a7bf6cd70c8767b02c97bf8134fa434daf3926cfc1be0a0f94132d165a"
dependencies = [
"tauri",
"tauri-plugin",
]
[[package]] [[package]]
name = "tauri-plugin-single-instance" name = "tauri-plugin-single-instance"
version = "2.4.2" version = "2.4.2"
@ -4920,7 +5128,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15edbb0d80583e85ee8df283410038e17314df5cba30da2087a54a85216c0773" checksum = "15edbb0d80583e85ee8df283410038e17314df5cba30da2087a54a85216c0773"
dependencies = [ dependencies = [
"crossbeam-channel", "crossbeam-channel",
"dirs", "dirs 6.0.0",
"libappindicator", "libappindicator",
"muda", "muda",
"objc2", "objc2",
@ -5236,6 +5444,19 @@ dependencies = [
"wasmparser", "wasmparser",
] ]
[[package]]
name = "wasm-streams"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65"
dependencies = [
"futures-util",
"js-sys",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
]
[[package]] [[package]]
name = "wasm-streams" name = "wasm-streams"
version = "0.5.0" version = "0.5.0"
@ -5605,6 +5826,15 @@ dependencies = [
"windows-targets 0.42.2", "windows-targets 0.42.2",
] ]
[[package]]
name = "windows-sys"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
dependencies = [
"windows-targets 0.48.5",
]
[[package]] [[package]]
name = "windows-sys" name = "windows-sys"
version = "0.52.0" version = "0.52.0"
@ -5656,6 +5886,21 @@ dependencies = [
"windows_x86_64_msvc 0.42.2", "windows_x86_64_msvc 0.42.2",
] ]
[[package]]
name = "windows-targets"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
dependencies = [
"windows_aarch64_gnullvm 0.48.5",
"windows_aarch64_msvc 0.48.5",
"windows_i686_gnu 0.48.5",
"windows_i686_msvc 0.48.5",
"windows_x86_64_gnu 0.48.5",
"windows_x86_64_gnullvm 0.48.5",
"windows_x86_64_msvc 0.48.5",
]
[[package]] [[package]]
name = "windows-targets" name = "windows-targets"
version = "0.52.6" version = "0.52.6"
@ -5713,6 +5958,12 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
[[package]] [[package]]
name = "windows_aarch64_gnullvm" name = "windows_aarch64_gnullvm"
version = "0.52.6" version = "0.52.6"
@ -5731,6 +5982,12 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
[[package]]
name = "windows_aarch64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
[[package]] [[package]]
name = "windows_aarch64_msvc" name = "windows_aarch64_msvc"
version = "0.52.6" version = "0.52.6"
@ -5749,6 +6006,12 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
[[package]]
name = "windows_i686_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
[[package]] [[package]]
name = "windows_i686_gnu" name = "windows_i686_gnu"
version = "0.52.6" version = "0.52.6"
@ -5779,6 +6042,12 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
[[package]]
name = "windows_i686_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
[[package]] [[package]]
name = "windows_i686_msvc" name = "windows_i686_msvc"
version = "0.52.6" version = "0.52.6"
@ -5797,6 +6066,12 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
[[package]]
name = "windows_x86_64_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
[[package]] [[package]]
name = "windows_x86_64_gnu" name = "windows_x86_64_gnu"
version = "0.52.6" version = "0.52.6"
@ -5815,6 +6090,12 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
[[package]] [[package]]
name = "windows_x86_64_gnullvm" name = "windows_x86_64_gnullvm"
version = "0.52.6" version = "0.52.6"
@ -5833,6 +6114,12 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
[[package]]
name = "windows_x86_64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
[[package]] [[package]]
name = "windows_x86_64_msvc" name = "windows_x86_64_msvc"
version = "0.52.6" version = "0.52.6"
@ -5989,7 +6276,7 @@ dependencies = [
"block2", "block2",
"cookie", "cookie",
"crossbeam-channel", "crossbeam-channel",
"dirs", "dirs 6.0.0",
"dom_query", "dom_query",
"dpi", "dpi",
"dunce", "dunce",
@ -6044,6 +6331,29 @@ dependencies = [
"pkg-config", "pkg-config",
] ]
[[package]]
name = "x11rb"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"
dependencies = [
"gethostname",
"rustix",
"x11rb-protocol",
]
[[package]]
name = "x11rb-protocol"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
[[package]]
name = "xkeysym"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
[[package]] [[package]]
name = "yoke" name = "yoke"
version = "0.8.2" version = "0.8.2"

View File

@ -1,6 +1,6 @@
[package] [package]
name = "Nekosonic" name = "Nekosonic"
version = "0.1.0" version = "0.3.0"
description = "A Simple music app" description = "A Simple music app"
authors = ["atdunbg"] authors = ["atdunbg"]
edition = "2021" edition = "2021"
@ -21,12 +21,19 @@ tauri-build = { version = "2", features = [] }
tauri = { version = "2", features = ["tray-icon"] } tauri = { version = "2", features = ["tray-icon"] }
tauri-plugin-opener = "2" tauri-plugin-opener = "2"
tauri-plugin-single-instance = "2" tauri-plugin-single-instance = "2"
tauri-plugin-global-shortcut = "2"
tauri-plugin-dialog = "2"
rodio = "0.20" rodio = "0.20"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
cpal = { version = "0.15" } cpal = { version = "0.15" }
reqwest = { version = "0.12", default-features = false, features = ["blocking", "rustls-tls"] } reqwest = { version = "0.12", default-features = false, features = ["blocking", "rustls-tls", "stream"] }
futures-util = "0.3"
dirs = "5"
lofty = "0.22"
base64 = "0.22"
ncm-api-rs = "0.1" ncm-api-rs = "0.1"
tokio = { version = "1", features = ["rt", "sync"] } tokio = { version = "1", features = ["rt", "sync"] }
tauri-plugin-process = "2.3.1"

View File

@ -15,6 +15,11 @@
"core:window:allow-toggle-maximize", "core:window:allow-toggle-maximize",
"core:window:allow-unminimize", "core:window:allow-unminimize",
"core:window:allow-show", "core:window:allow-show",
"core:window:allow-set-focus" "core:window:allow-set-focus",
"global-shortcut:allow-is-registered",
"global-shortcut:allow-register",
"global-shortcut:allow-unregister",
"dialog:allow-open",
"process:allow-restart"
] ]
} }

View File

@ -1,12 +1,18 @@
use ncm_api_rs::{create_client, ApiClient, Query}; use ncm_api_rs::{create_client, ApiClient, Query};
use serde::Deserialize; use serde::Deserialize;
use tauri::{Manager, State}; use serde_json::json;
use tauri::{Manager, State, Emitter};
use tokio::sync::Mutex; use tokio::sync::Mutex;
use std::sync::Mutex as StdMutex; use std::sync::Mutex as StdMutex;
use std::sync::atomic::Ordering; use std::sync::atomic::Ordering;
use std::fs; use std::fs;
use std::path::PathBuf; use std::path::PathBuf;
use std::io::Write;
use std::hash::{Hash, Hasher};
use lofty::file::{AudioFile, TaggedFileExt};
use lofty::tag::Accessor;
use base64::Engine;
pub struct ApiController { pub struct ApiController {
client: Mutex<ApiClient>, client: Mutex<ApiClient>,
@ -103,21 +109,54 @@ pub async fn playlist_track_all(query: PlaylistTrackAllQuery, state: State<'_, A
} }
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct SongUrlQuery { pub id: u64, pub level: Option<String> } pub struct SongUrlQuery { pub id: u64, pub level: Option<String>, pub fm_mode: Option<bool> }
/// 获取歌曲播放地址 /// 获取歌曲播放地址(返回完整 data 对象,包含 url、freeTrialInfo 等)
#[tauri::command] #[tauri::command]
pub async fn get_song_url(query: SongUrlQuery, state: State<'_, ApiController>) -> Result<String, String> { pub async fn get_song_url(query: SongUrlQuery, state: State<'_, ApiController>) -> Result<String, String> {
let client = state.client.lock().await; let client = state.client.lock().await;
let level = query.level.as_deref().unwrap_or("standard"); let level = query.level.as_deref().unwrap_or("standard");
let resp = if query.fm_mode.unwrap_or(false) {
let mut fm_cookie = state.cookie.lock().ok().and_then(|g| g.clone()).unwrap_or_default();
if !fm_cookie.contains("os=") {
fm_cookie = format!("{}; os=android; appver=8.10.05", fm_cookie);
}
let data = serde_json::json!({
"ids": format!("[{}]", query.id),
"level": level,
"encodeType": "flac",
"feeProcess": "true"
});
let option = ncm_api_rs::request::RequestOption {
crypto: ncm_api_rs::request::CryptoType::default(),
cookie: Some(fm_cookie),
ua: None,
proxy: None,
real_ip: None,
random_cn_ip: false,
e_r: None,
domain: None,
check_token: false,
};
client.request(
"/api/song/enhance/player/url/v1",
data,
option,
).await.map_err(|e| e.to_string())?
} else {
let q = state.build_query() let q = state.build_query()
.param("id", &query.id.to_string()) .param("id", &query.id.to_string())
.param("level", level); .param("level", level);
let resp = client.song_url_v1(&q).await.map_err(|e| e.to_string())?; client.song_url_v1(&q).await.map_err(|e| e.to_string())?
resp.body["data"][0]["url"].as_str() };
.filter(|s| !s.is_empty())
.map(|s| s.to_string()) let data = &resp.body["data"][0];
.ok_or_else(|| "暂无播放源".into()) let url = data["url"].as_str().filter(|s| !s.is_empty());
if url.is_none() {
return Err("暂无播放源".into());
}
Ok(data.to_string())
} }
/// 获取歌词 /// 获取歌词
@ -340,3 +379,352 @@ pub async fn exit_app(app_handle: tauri::AppHandle) {
let _ = window.close(); let _ = window.close();
} }
} }
#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LocalSongInfo {
pub id: u64,
pub name: String,
pub artist: String,
pub album: String,
pub duration: u64,
pub cover: Option<String>,
pub filename: String,
pub file_size: u64,
pub path: String,
pub local: bool,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DownloadSongQuery {
pub id: u64,
pub name: String,
pub artist: String,
pub album: Option<String>,
pub duration: Option<u64>,
pub cover_url: Option<String>,
pub level: Option<String>,
pub download_path: Option<String>,
}
#[tauri::command]
pub async fn download_song(
app_handle: tauri::AppHandle,
query: DownloadSongQuery,
state: State<'_, ApiController>,
) -> Result<String, String> {
let level = query.level.as_deref().unwrap_or("standard");
let q = state.build_query()
.param("id", &query.id.to_string())
.param("level", level);
let client = state.client.lock().await;
let resp = client.song_url_v1(&q).await.map_err(|e| e.to_string())?;
let data = &resp.body["data"][0];
let url = data["url"].as_str().filter(|s| !s.is_empty());
if url.is_none() {
let free_trial = data.get("freeTrialInfo");
if free_trial.is_some() && !free_trial.unwrap().is_null() {
return Err("VIP歌曲无法下载".into());
}
return Err("暂无下载源,可能需要 VIP 权限".into());
}
let url = url.unwrap();
let free_trial = data.get("freeTrialInfo");
if free_trial.is_some() && !free_trial.unwrap().is_null() {
return Err("VIP歌曲无法下载".into());
}
let ext = if url.contains(".flac") { "flac" } else { "mp3" };
drop(client);
let download_dir = resolve_download_dir(&app_handle, query.download_path.as_deref());
let _ = fs::create_dir_all(&download_dir);
let safe_name = sanitize_filename(&query.name);
let safe_artist = sanitize_filename(&query.artist);
let filename = format!("{} - {}.{}", safe_artist, safe_name, ext);
let filepath = download_dir.join(&filename);
if filepath.exists() {
return Err("文件已存在".into());
}
let resp = reqwest::get(url).await.map_err(|e| format!("下载失败: {}", e))?;
let total_size = resp.content_length().unwrap_or(0);
let mut downloaded: u64 = 0;
let temp_path = filepath.with_extension(format!("{}.tmp", ext));
let mut file = fs::File::create(&temp_path).map_err(|e| format!("创建文件失败: {}", e))?;
let mut stream = resp.bytes_stream();
use futures_util::StreamExt;
let mut chunk_count: u64 = 0;
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(|e| format!("读取失败: {}", e))?;
file.write_all(&chunk).map_err(|e| format!("写入失败: {}", e))?;
downloaded += chunk.len() as u64;
chunk_count += 1;
if chunk_count % 8 == 0 || downloaded == total_size {
let progress = if total_size > 0 {
(downloaded as f64 / total_size as f64) * 100.0
} else {
0.0
};
let _ = app_handle.emit("download-progress", json!({
"id": query.id,
"progress": progress,
"name": query.name,
}));
}
}
drop(file);
fs::rename(&temp_path, &filepath).map_err(|e| format!("重命名失败: {}", e))?;
let meta = json!({
"id": query.id,
"name": query.name,
"artist": query.artist,
"album": query.album,
"duration": query.duration,
"coverUrl": query.cover_url,
"filename": filename,
});
let meta_path = download_dir.join(format!("{}.json", query.id));
let mut meta_file = fs::File::create(&meta_path).map_err(|e| format!("创建元数据失败: {}", e))?;
meta_file.write_all(serde_json::to_string_pretty(&meta).unwrap().as_bytes())
.map_err(|e| format!("写入元数据失败: {}", e))?;
let _ = app_handle.emit("download-progress", json!({
"id": query.id,
"progress": 100.0,
"name": query.name,
}));
Ok(filename)
}
#[tauri::command]
pub fn list_local_songs(app_handle: tauri::AppHandle, download_path: Option<String>) -> Result<Vec<LocalSongInfo>, String> {
let download_dir = resolve_download_dir(&app_handle, download_path.as_deref());
if !download_dir.exists() {
return Ok(Vec::new());
}
let audio_exts = ["mp3", "flac", "wav", "ogg", "aac", "m4a", "wma", "opus"];
let mut meta_map: std::collections::HashMap<String, serde_json::Value> = std::collections::HashMap::new();
let entries = fs::read_dir(&download_dir).map_err(|e| format!("读取目录失败: {}", e))?;
for entry in entries.flatten() {
let path = entry.path();
if path.extension().map_or(false, |e| e == "json") {
if let Ok(content) = fs::read_to_string(&path) {
if let Ok(meta) = serde_json::from_str::<serde_json::Value>(&content) {
if let Some(filename) = meta["filename"].as_str() {
meta_map.insert(filename.to_string(), meta);
}
}
}
}
}
let mut songs: Vec<LocalSongInfo> = Vec::new();
let entries = fs::read_dir(&download_dir).map_err(|e| format!("读取目录失败: {}", e))?;
for entry in entries.flatten() {
let path = entry.path();
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
if !audio_exts.contains(&ext.to_lowercase().as_str()) {
continue;
}
let filename = path.file_name().unwrap_or_default().to_string_lossy().to_string();
let file_size = fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
let (title, artist, album, duration_ms, cover_b64) = read_audio_metadata(&path);
if let Some(meta) = meta_map.get(&filename) {
let meta_title = meta["name"].as_str().unwrap_or("");
let meta_artist = meta["artist"].as_str().unwrap_or("");
let meta_album = meta["album"].as_str().unwrap_or("");
let meta_duration = meta["duration"].as_u64().unwrap_or(0);
let meta_cover_url = meta["coverUrl"].as_str().unwrap_or("");
let final_title = if title.is_empty() { meta_title.to_string() } else { title };
let final_artist = if artist.is_empty() { meta_artist.to_string() } else { artist };
let final_album = if album.is_empty() { meta_album.to_string() } else { album };
let final_duration = if duration_ms == 0 { meta_duration } else { duration_ms };
let final_cover = cover_b64.or_else(|| {
if meta_cover_url.is_empty() { None } else { Some(meta_cover_url.to_string()) }
});
songs.push(LocalSongInfo {
id: meta["id"].as_u64().unwrap_or(0),
name: final_title,
artist: final_artist,
album: final_album,
duration: final_duration,
cover: final_cover,
filename,
file_size,
path: path.to_string_lossy().to_string(),
local: true,
});
} else {
let stem = path.file_stem().unwrap_or_default().to_string_lossy().to_string();
let (parsed_artist, parsed_name) = parse_filename(&stem);
let final_title = if title.is_empty() { parsed_name } else { title };
let final_artist = if artist.is_empty() { parsed_artist } else { artist };
let mut hasher = std::collections::hash_map::DefaultHasher::new();
filename.hash(&mut hasher);
let hash_id = hasher.finish();
songs.push(LocalSongInfo {
id: hash_id,
name: final_title,
artist: final_artist,
album,
duration: duration_ms,
cover: cover_b64,
filename,
file_size,
path: path.to_string_lossy().to_string(),
local: true,
});
}
}
Ok(songs)
}
fn read_audio_metadata(path: &PathBuf) -> (String, String, String, u64, Option<String>) {
match lofty::read_from_path(path) {
Ok(tagged_file) => {
let properties = tagged_file.properties();
let duration_ms = properties.duration().as_millis() as u64;
let tag = tagged_file.primary_tag();
let (title, artist, album) = if let Some(t) = tag {
let title = t.title().map(|s| s.to_string()).unwrap_or_default();
let artist = t.artist().map(|s| s.to_string()).unwrap_or_default();
let album = t.album().map(|s| s.to_string()).unwrap_or_default();
(title, artist, album)
} else {
(String::new(), String::new(), String::new())
};
let cover_b64 = if let Some(t) = tag {
if let Some(pic) = t.pictures().first() {
let data = pic.data();
let mime = pic.mime_type().map(|m| m.to_string()).unwrap_or_else(|| "image/jpeg".to_string());
let b64 = base64::engine::general_purpose::STANDARD.encode(data);
Some(format!("data:{};base64,{}", mime, b64))
} else {
None
}
} else {
None
};
(title, artist, album, duration_ms, cover_b64)
}
Err(e) => {
eprintln!("[api] 读取音频元数据失败 {}: {}", path.display(), e);
(String::new(), String::new(), String::new(), 0, None)
}
}
}
fn parse_filename(stem: &str) -> (String, String) {
if let Some(pos) = stem.find(" - ") {
let artist = &stem[..pos];
let name = &stem[pos + 3..];
(artist.trim().to_string(), name.trim().to_string())
} else if let Some(pos) = stem.find('-') {
let artist = &stem[..pos];
let name = &stem[pos + 1..];
(artist.trim().to_string(), name.trim().to_string())
} else {
("".to_string(), stem.trim().to_string())
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeleteLocalSongQuery {
pub id: u64,
pub filename: String,
pub download_path: Option<String>,
}
#[tauri::command]
pub fn delete_local_song(
app_handle: tauri::AppHandle,
query: DeleteLocalSongQuery,
) -> Result<(), String> {
let download_dir = resolve_download_dir(&app_handle, query.download_path.as_deref());
let file_path = download_dir.join(&query.filename);
let meta_path = download_dir.join(format!("{}.json", query.id));
if file_path.exists() {
fs::remove_file(&file_path).map_err(|e| format!("删除文件失败: {}", e))?;
}
if meta_path.exists() {
fs::remove_file(&meta_path).map_err(|e| format!("删除元数据失败: {}", e))?;
}
Ok(())
}
#[tauri::command]
pub fn check_local_song(app_handle: tauri::AppHandle, id: u64, download_path: Option<String>) -> Result<bool, String> {
let download_dir = resolve_download_dir(&app_handle, download_path.as_deref());
let meta_path = download_dir.join(format!("{}.json", id));
Ok(meta_path.exists())
}
fn resolve_download_dir(app_handle: &tauri::AppHandle, custom_path: Option<&str>) -> PathBuf {
if let Some(path) = custom_path {
if !path.is_empty() {
return PathBuf::from(path);
}
}
get_default_download_dir(app_handle)
}
fn get_default_download_dir(app_handle: &tauri::AppHandle) -> PathBuf {
if let Ok(dir) = app_handle.path().app_data_dir() {
let download_dir = dir.join("downloads");
return download_dir;
}
let music_dir = dirs::audio_dir().unwrap_or_else(|| {
std::env::var("HOME")
.or_else(|_| std::env::var("USERPROFILE"))
.map(PathBuf::from)
.unwrap_or_else(|_| PathBuf::from("."))
});
music_dir.join("Nekosonic")
}
#[tauri::command]
pub fn get_default_download_path(app_handle: tauri::AppHandle) -> String {
get_default_download_dir(&app_handle).to_string_lossy().to_string()
}
fn sanitize_filename(name: &str) -> String {
name.chars()
.map(|c| {
if c == '/' || c == '\\' || c == ':' || c == '*' || c == '?'
|| c == '"' || c == '<' || c == '>' || c == '|'
{
'_'
} else {
c
}
})
.collect::<String>()
.trim()
.to_string()
}

View File

@ -1,8 +1,8 @@
use rodio::{Decoder, OutputStream, Sink, Source}; use rodio::{Decoder, OutputStream, Sink, Source};
use rodio::cpal::traits::{DeviceTrait, HostTrait}; use rodio::cpal::traits::{DeviceTrait, HostTrait};
use std::io::Cursor; use std::io::{Read, Seek, SeekFrom};
use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Condvar, Mutex};
use std::thread; use std::thread;
use std::time::Duration; use std::time::Duration;
use tauri::AppHandle; use tauri::AppHandle;
@ -11,6 +11,7 @@ use tauri::Emitter;
// ---------- 命令 ---------- // ---------- 命令 ----------
enum AudioCmd { enum AudioCmd {
Play(String), Play(String),
PlayLocal(String),
Pause, Pause,
Resume, Resume,
Stop, Stop,
@ -29,18 +30,22 @@ impl AudioController {
let (tx, rx) = channel(); let (tx, rx) = channel();
let current_url = Arc::new(Mutex::new(None)); let current_url = Arc::new(Mutex::new(None));
let url_clone = current_url.clone(); let url_clone = current_url.clone();
let ah_clone = app_handle.clone(); // 克隆一个用于闭包 let ah_clone = app_handle.clone();
thread::spawn(move || audio_thread(rx, url_clone, ah_clone)); thread::spawn(move || audio_thread(rx, url_clone, ah_clone));
AudioController { AudioController {
tx, tx,
current_url, current_url,
} }
} }
pub fn play_url(&self, url: &str) { pub fn play_url(&self, url: &str) {
*self.current_url.lock().unwrap() = Some(url.to_string()); *self.current_url.lock().unwrap() = Some(url.to_string());
let _ = self.tx.send(AudioCmd::Play(url.to_string())); let _ = self.tx.send(AudioCmd::Play(url.to_string()));
} }
pub fn play_local(&self, path: &str) {
*self.current_url.lock().unwrap() = Some(path.to_string());
let _ = self.tx.send(AudioCmd::PlayLocal(path.to_string()));
}
pub fn pause(&self) { let _ = self.tx.send(AudioCmd::Pause); } pub fn pause(&self) { let _ = self.tx.send(AudioCmd::Pause); }
pub fn resume(&self) { let _ = self.tx.send(AudioCmd::Resume); } pub fn resume(&self) { let _ = self.tx.send(AudioCmd::Resume); }
pub fn stop(&self) { let _ = self.tx.send(AudioCmd::Stop); } pub fn stop(&self) { let _ = self.tx.send(AudioCmd::Stop); }
@ -55,44 +60,179 @@ impl AudioController {
} }
} }
use std::io::Read; // ---------- 流式缓冲区 ----------
fn download_audio_with_progress( struct BufferState {
bytes: Vec<u8>,
done: bool,
cancelled: bool,
}
struct SharedBuffer {
state: Mutex<BufferState>,
available: Condvar,
}
impl SharedBuffer {
fn new() -> Self {
SharedBuffer {
state: Mutex::new(BufferState {
bytes: Vec::new(),
done: false,
cancelled: false,
}),
available: Condvar::new(),
}
}
fn write_chunk(&self, chunk: &[u8]) {
let mut state = self.state.lock().unwrap();
state.bytes.extend_from_slice(chunk);
self.available.notify_all();
}
fn mark_done(&self) {
let mut state = self.state.lock().unwrap();
state.done = true;
self.available.notify_all();
}
fn cancel(&self) {
let mut state = self.state.lock().unwrap();
state.cancelled = true;
self.available.notify_all();
}
fn len(&self) -> usize {
self.state.lock().unwrap().bytes.len()
}
fn is_done(&self) -> bool {
self.state.lock().unwrap().done
}
fn is_cancelled(&self) -> bool {
self.state.lock().unwrap().cancelled
}
}
struct StreamingReader {
buffer: Arc<SharedBuffer>,
pos: usize,
}
impl StreamingReader {
fn new(buffer: Arc<SharedBuffer>) -> Self {
StreamingReader { buffer, pos: 0 }
}
}
impl Read for StreamingReader {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let mut state = self.buffer.state.lock().unwrap();
loop {
let available = state.bytes.len().saturating_sub(self.pos);
if available > 0 {
let to_read = std::cmp::min(buf.len(), available);
buf[..to_read].copy_from_slice(&state.bytes[self.pos..self.pos + to_read]);
self.pos += to_read;
return Ok(to_read);
}
if state.done {
return Ok(0);
}
if state.cancelled {
return Err(std::io::Error::new(std::io::ErrorKind::Interrupted, "cancelled"));
}
let result = self.buffer.available.wait_timeout(state, Duration::from_millis(500)).unwrap();
state = result.0;
}
}
}
impl Seek for StreamingReader {
fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
let new_pos = match pos {
SeekFrom::Start(offset) => offset as i64,
SeekFrom::Current(offset) => self.pos as i64 + offset,
SeekFrom::End(offset) => {
let mut state = self.buffer.state.lock().unwrap();
loop {
if state.done {
break state.bytes.len() as i64 + offset;
}
if state.cancelled {
return Err(std::io::Error::new(std::io::ErrorKind::Interrupted, "cancelled"));
}
let result = self.buffer.available.wait_timeout(state, Duration::from_millis(500)).unwrap();
state = result.0;
}
}
};
if new_pos < 0 {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "seek before start"));
}
let mut state = self.buffer.state.lock().unwrap();
loop {
if new_pos as usize <= state.bytes.len() {
self.pos = new_pos as usize;
return Ok(self.pos as u64);
}
if state.done {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "seek past end"));
}
if state.cancelled {
return Err(std::io::Error::new(std::io::ErrorKind::Interrupted, "cancelled"));
}
let result = self.buffer.available.wait_timeout(state, Duration::from_millis(500)).unwrap();
state = result.0;
}
}
}
fn download_audio_streaming(
url: &str, url: &str,
buffer: &SharedBuffer,
app_handle: &AppHandle, app_handle: &AppHandle,
) -> Result<Vec<u8>, String> { ) -> Result<(), String> {
let resp = reqwest::blocking::get(url) let resp = reqwest::blocking::get(url)
.map_err(|e| format!("下载失败: {}", e))?; .map_err(|e| format!("下载失败: {}", e))?;
if !resp.status().is_success() {
return Err(format!("HTTP 错误: {}", resp.status()));
}
let total_size = resp.content_length().unwrap_or(0); let total_size = resp.content_length().unwrap_or(0);
let mut downloaded: u64 = 0; let mut downloaded: u64 = 0;
let mut buffer = Vec::new();
let mut reader = resp; let mut reader = resp;
loop { loop {
if buffer.is_cancelled() {
return Err("下载已取消".to_string());
}
let mut chunk = [0u8; 8192]; let mut chunk = [0u8; 8192];
let read_size = reader.read(&mut chunk) let read_size = reader.read(&mut chunk)
.map_err(|e| format!("读取失败: {}", e))?; .map_err(|e| format!("读取失败: {}", e))?;
if read_size == 0 { if read_size == 0 {
break; break;
} }
buffer.extend_from_slice(&chunk[..read_size]); buffer.write_chunk(&chunk[..read_size]);
downloaded += read_size as u64; downloaded += read_size as u64;
// 发送进度事件给前端(每 8192 字节发一次,不必太频繁)
let progress = if total_size > 0 { let progress = if total_size > 0 {
(downloaded as f64 / total_size as f64) * 100.0 (downloaded as f64 / total_size as f64) * 100.0
} else { } else {
0.0 // 未知大小时为 0 0.0
}; };
let _ = app_handle.emit("cache-progress", progress); let _ = app_handle.emit("cache-progress", progress);
} }
// 下载完成,确保进度为 100 Ok(())
let _ = app_handle.emit("cache-progress", 100f64);
Ok(buffer)
} }
const INITIAL_BUFFER_SIZE: usize = 65536;
// ---------- 音频线程 ---------- // ---------- 音频线程 ----------
fn audio_thread(rx: Receiver<AudioCmd>, current_url: Arc<Mutex<Option<String>>>, app_handle: AppHandle) { fn audio_thread(rx: Receiver<AudioCmd>, current_url: Arc<Mutex<Option<String>>>, app_handle: AppHandle) {
let mut selected_device: Option<String> = None; let mut selected_device: Option<String> = None;
@ -104,47 +244,148 @@ fn audio_thread(rx: Receiver<AudioCmd>, current_url: Arc<Mutex<Option<String>>>,
sink.set_volume(current_volume); sink.set_volume(current_volume);
} }
let mut current_audio_data: Option<Vec<u8>> = None; // 缓存原始音频字节 let mut current_audio_buffer: Option<Arc<SharedBuffer>> = None;
let mut audio_active = false;
let mut audio_paused = false;
let mut manual_stop = false;
loop { loop {
match rx.recv_timeout(Duration::from_millis(200)) { match rx.recv_timeout(Duration::from_millis(200)) {
Ok(cmd) => { Ok(cmd) => {
match cmd { match cmd {
AudioCmd::Play(url) => { AudioCmd::Play(url) => {
// 停止旧播放并重建干净输出 audio_active = false;
if let Some(ref sink) = output.sink { audio_paused = false;
sink.stop(); manual_stop = false;
if let Some(ref buf) = current_audio_buffer {
buf.cancel();
} }
if let Some(ref sink) = output.sink { sink.stop(); }
output = create_output(&selected_device); output = create_output(&selected_device);
if let Some(ref sink) = output.sink { if let Some(ref sink) = output.sink {
sink.set_volume(current_volume); sink.set_volume(current_volume);
match download_audio_with_progress(&url, &app_handle) { let buffer = Arc::new(SharedBuffer::new());
current_audio_buffer = Some(buffer.clone());
let buffer_clone = buffer.clone();
let ah_clone = app_handle.clone();
let url_clone = url.clone();
thread::spawn(move || {
if let Err(e) = download_audio_streaming(&url_clone, &buffer_clone, &ah_clone) {
if !buffer_clone.is_cancelled() {
eprintln!("[audio] 流式下载失败: {}", e);
}
}
buffer_clone.mark_done();
});
loop {
let len = buffer.len();
if len >= INITIAL_BUFFER_SIZE || buffer.is_done() || buffer.is_cancelled() {
break;
}
std::thread::sleep(Duration::from_millis(50));
}
if buffer.is_cancelled() || buffer.len() == 0 {
current_audio_buffer = None;
continue;
}
let reader = StreamingReader::new(buffer.clone());
match Decoder::new(reader) {
Ok(source) => {
sink.append(source);
sink.play();
audio_active = true;
let _ = app_handle.emit("audio-started", ());
}
Err(e) => {
eprintln!("[audio] 流式解码失败: {}, 等待完整下载后重试", e);
loop {
if buffer.is_done() || buffer.is_cancelled() {
break;
}
std::thread::sleep(Duration::from_millis(100));
}
if buffer.is_cancelled() || buffer.len() == 0 {
current_audio_buffer = None;
continue;
}
let buf = current_audio_buffer.as_ref().unwrap().clone();
let reader2 = StreamingReader::new(buf);
match Decoder::new(reader2) {
Ok(source) => {
sink.append(source);
sink.play();
audio_active = true;
let _ = app_handle.emit("audio-started", ());
}
Err(e2) => {
eprintln!("[audio] 完整下载后解码也失败: {}", e2);
}
}
}
}
}
}
AudioCmd::PlayLocal(path) => {
audio_active = false;
audio_paused = false;
manual_stop = false;
if let Some(ref buf) = current_audio_buffer {
buf.cancel();
}
if let Some(ref sink) = output.sink { sink.stop(); }
output = create_output(&selected_device);
if let Some(ref sink) = output.sink {
sink.set_volume(current_volume);
match std::fs::read(&path) {
Ok(bytes) => { Ok(bytes) => {
current_audio_data = Some(bytes.clone()); let buffer = Arc::new(SharedBuffer::new());
let play_res = play_bytes(&bytes, sink); buffer.write_chunk(&bytes);
if let Err(e) = play_res { buffer.mark_done();
eprintln!("[audio] 播放失败: {}", e); current_audio_buffer = Some(buffer.clone());
let reader = StreamingReader::new(buffer);
match Decoder::new(reader) {
Ok(source) => {
sink.append(source);
sink.play();
audio_active = true;
let _ = app_handle.emit("audio-started", ());
}
Err(e) => eprintln!("[audio] 本地播放失败: {}", e),
} }
} }
Err(e) => eprintln!("[audio] 下载失败: {}", e), Err(e) => eprintln!("[audio] 读取本地文件失败: {}", e),
} }
} }
} }
AudioCmd::Pause => { AudioCmd::Pause => {
audio_paused = true;
if let Some(ref sink) = output.sink { sink.pause(); } if let Some(ref sink) = output.sink { sink.pause(); }
} }
AudioCmd::Resume => { AudioCmd::Resume => {
audio_paused = false;
if let Some(ref sink) = output.sink { sink.play(); } if let Some(ref sink) = output.sink { sink.play(); }
} }
AudioCmd::Stop => { AudioCmd::Stop => {
audio_active = false;
audio_paused = false;
manual_stop = true;
if let Some(ref buf) = current_audio_buffer {
buf.cancel();
}
if let Some(ref sink) = output.sink { sink.stop(); } if let Some(ref sink) = output.sink { sink.stop(); }
} }
AudioCmd::Seek(time) => { AudioCmd::Seek(time) => {
if let Some(ref sink) = output.sink { if let Some(ref sink) = output.sink {
// 优先尝试高效的 sink.try_seek毫秒级
let seek_res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let seek_res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
sink.try_seek(Duration::from_secs_f64(time)) sink.try_seek(Duration::from_secs_f64(time))
})); }));
@ -153,19 +394,34 @@ fn audio_thread(rx: Receiver<AudioCmd>, current_url: Arc<Mutex<Option<String>>>,
Ok(Ok(_)) => { /* 成功 */ } Ok(Ok(_)) => { /* 成功 */ }
Ok(Err(e)) => { Ok(Err(e)) => {
eprintln!("[audio] try_seek 失败: {:?}, 回退重建解码", e); eprintln!("[audio] try_seek 失败: {:?}, 回退重建解码", e);
// 回退方案:重新解码并从目标时间开始 if let Some(ref buffer) = current_audio_buffer {
if let Some(ref bytes) = current_audio_data {
sink.stop(); sink.stop();
sink.clear(); sink.clear();
let _ = play_bytes_with_seek(bytes, sink, time); let reader = StreamingReader::new(buffer.clone());
match Decoder::new(reader) {
Ok(source) => {
let source = source.skip_duration(Duration::from_secs_f64(time));
sink.append(source);
sink.play();
}
Err(e) => eprintln!("[audio] seek 解码失败: {}", e),
}
} }
} }
Err(_) => { Err(_) => {
eprintln!("[audio] try_seek 崩溃,回退重建解码"); eprintln!("[audio] try_seek 崩溃,回退重建解码");
if let Some(ref bytes) = current_audio_data { if let Some(ref buffer) = current_audio_buffer {
sink.stop(); sink.stop();
sink.clear(); sink.clear();
let _ = play_bytes_with_seek(bytes, sink, time); let reader = StreamingReader::new(buffer.clone());
match Decoder::new(reader) {
Ok(source) => {
let source = source.skip_duration(Duration::from_secs_f64(time));
sink.append(source);
sink.play();
}
Err(e) => eprintln!("[audio] seek 解码失败: {}", e),
}
} }
} }
} }
@ -184,10 +440,16 @@ fn audio_thread(rx: Receiver<AudioCmd>, current_url: Arc<Mutex<Option<String>>>,
output = create_output(&selected_device); output = create_output(&selected_device);
if let Some(ref sink) = output.sink { if let Some(ref sink) = output.sink {
sink.set_volume(current_volume); sink.set_volume(current_volume);
// 如果正在播放,恢复播放
if current_url.lock().unwrap().is_some() { if current_url.lock().unwrap().is_some() {
if let Some(ref bytes) = current_audio_data { if let Some(ref buffer) = current_audio_buffer {
let _ = play_bytes(bytes, sink); let reader = StreamingReader::new(buffer.clone());
match Decoder::new(reader) {
Ok(source) => {
sink.append(source);
sink.play();
}
Err(e) => eprintln!("[audio] 设备切换解码失败: {}", e),
}
} }
} }
} }
@ -199,7 +461,16 @@ fn audio_thread(rx: Receiver<AudioCmd>, current_url: Arc<Mutex<Option<String>>>,
} }
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
// 跟随系统默认设备变化 if audio_active && !audio_paused {
if let Some(ref sink) = output.sink {
if sink.empty() {
audio_active = false;
if !manual_stop {
let _ = app_handle.emit("audio-ended", ());
}
}
}
}
if selected_device.is_none() { if selected_device.is_none() {
let current_default = get_system_default_device_name(); let current_default = get_system_default_device_name();
if current_default != last_default_name { if current_default != last_default_name {
@ -208,8 +479,12 @@ fn audio_thread(rx: Receiver<AudioCmd>, current_url: Arc<Mutex<Option<String>>>,
output = create_output(&selected_device); output = create_output(&selected_device);
if let Some(ref sink) = output.sink { if let Some(ref sink) = output.sink {
sink.set_volume(current_volume); sink.set_volume(current_volume);
if let Some(ref bytes) = current_audio_data { if let Some(ref buffer) = current_audio_buffer {
let _ = play_bytes(bytes, sink); let reader = StreamingReader::new(buffer.clone());
let _ = Decoder::new(reader).map(|source| {
sink.append(source);
sink.play();
});
} }
} }
} }
@ -220,28 +495,7 @@ fn audio_thread(rx: Receiver<AudioCmd>, current_url: Arc<Mutex<Option<String>>>,
} }
} }
// ---------- 播放辅助函数 ---------- // ---------- 其余函数保持不变 ----------
/// 直接播放字节数据
fn play_bytes(bytes: &[u8], sink: &Sink) -> Result<(), String> {
let cursor = Cursor::new(bytes.to_vec());
let source = Decoder::new(cursor).map_err(|e| format!("解码失败: {}", e))?;
sink.append(source);
sink.play();
Ok(())
}
/// 播放字节数据并跳过指定秒数(用于 seek 回退)
fn play_bytes_with_seek(bytes: &[u8], sink: &Sink, seek_secs: f64) -> Result<(), String> {
let cursor = Cursor::new(bytes.to_vec());
let source = Decoder::new(cursor).map_err(|e| format!("解码失败: {}", e))?;
let source = source.skip_duration(Duration::from_secs_f64(seek_secs));
sink.append(source);
sink.play();
Ok(())
}
// ---------- 其余函数保持不变(获取设备、创建输出等) ----------
fn get_system_default_device_name() -> Option<String> { fn get_system_default_device_name() -> Option<String> {
rodio::cpal::default_host() rodio::cpal::default_host()
@ -340,6 +594,13 @@ pub fn play_audio(state: State<'_, AppAudio>, url: String) -> Result<(), String>
Ok(()) Ok(())
} }
#[tauri::command]
pub fn play_local_audio(state: State<'_, AppAudio>, path: String) -> Result<(), String> {
let ctrl = state.0.lock().map_err(|e| e.to_string())?;
ctrl.play_local(&path);
Ok(())
}
#[tauri::command] #[tauri::command]
pub fn pause_audio(state: State<'_, AppAudio>) { pub fn pause_audio(state: State<'_, AppAudio>) {
if let Ok(ctrl) = state.0.lock() { ctrl.pause(); } if let Ok(ctrl) = state.0.lock() { ctrl.pause(); }

View File

@ -56,6 +56,7 @@ pub fn run() {
"show" => { "show" => {
window.show().unwrap(); window.show().unwrap();
window.set_focus().unwrap(); window.set_focus().unwrap();
let _ = app.emit("window-shown", ());
} }
"play_pause" => { "play_pause" => {
let _ = app.emit("tray-play-pause", ()); let _ = app.emit("tray-play-pause", ());
@ -86,6 +87,7 @@ pub fn run() {
let window = app.get_webview_window("main").unwrap(); let window = app.get_webview_window("main").unwrap();
window.show().unwrap(); window.show().unwrap();
window.set_focus().unwrap(); window.set_focus().unwrap();
let _ = app.emit("window-shown", ());
} }
}) })
.build(app)?; .build(app)?;
@ -93,6 +95,7 @@ pub fn run() {
// 点击关闭按钮时隐藏到托盘 // 点击关闭按钮时隐藏到托盘
let window = app.get_webview_window("main").unwrap(); let window = app.get_webview_window("main").unwrap();
let window_clone = window.clone(); let window_clone = window.clone();
let app_handle = app.handle().clone();
window.on_window_event(move |event| { window.on_window_event(move |event| {
if let tauri::WindowEvent::CloseRequested { api: close_api, .. } = event { if let tauri::WindowEvent::CloseRequested { api: close_api, .. } = event {
if ALLOW_EXIT.load(Ordering::SeqCst) { if ALLOW_EXIT.load(Ordering::SeqCst) {
@ -100,6 +103,7 @@ pub fn run() {
} }
close_api.prevent_close(); close_api.prevent_close();
let _ = window_clone.hide(); let _ = window_clone.hide();
let _ = app_handle.emit("window-hidden", ());
} }
}); });
@ -132,20 +136,31 @@ pub fn run() {
api::exit_app, api::exit_app,
audio::play_audio, audio::play_audio,
audio::play_local_audio,
audio::pause_audio, audio::pause_audio,
audio::resume_audio, audio::resume_audio,
audio::stop_audio, audio::stop_audio,
audio::get_output_devices, audio::get_output_devices,
audio::set_output_device, audio::set_output_device,
audio::seek_audio, audio::seek_audio,
audio::set_volume audio::set_volume,
api::download_song,
api::list_local_songs,
api::delete_local_song,
api::check_local_song,
api::get_default_download_path
]) ])
.plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_global_shortcut::Builder::new().build())
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| { .plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
if let Some(window) = app.get_webview_window("main") { if let Some(window) = app.get_webview_window("main") {
let _ = window.show(); let _ = window.show();
let _ = window.set_focus(); let _ = window.set_focus();
let _ = window.unminimize(); let _ = window.unminimize();
let _ = app.emit("window-shown", ());
} }
})) }))
.run(tauri::generate_context!()) .run(tauri::generate_context!())

View File

@ -1,7 +1,7 @@
{ {
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"productName": "Nekosonic", "productName": "Nekosonic",
"version": "0.2.0", "version": "0.3.0",
"identifier": "com.atdunbg.Nekosonic", "identifier": "com.atdunbg.Nekosonic",
"build": { "build": {
"beforeDevCommand": "npm run dev", "beforeDevCommand": "npm run dev",
@ -34,6 +34,11 @@
"icons/128x128@2x.png", "icons/128x128@2x.png",
"icons/icon.icns", "icons/icon.icns",
"icons/icon.ico" "icons/icon.ico"
] ],
"windows": {
"webviewInstallMode": {
"type": "downloadBootstrapper"
}
}
} }
} }

View File

@ -12,7 +12,7 @@
</div> </div>
</div> </div>
<div class="flex flex-1 overflow-hidden"> <div class="flex flex-1 overflow-hidden" v-if="windowVisible">
<nav class="w-56 flex-shrink-0 flex flex-col bg-surface/80 backdrop-blur"> <nav class="w-56 flex-shrink-0 flex flex-col bg-surface/80 backdrop-blur">
<div class="flex-1 p-4 overflow-y-auto min-h-0"> <div class="flex-1 p-4 overflow-y-auto min-h-0">
<div class="flex flex-col min-h-full"> <div class="flex flex-col min-h-full">
@ -52,6 +52,12 @@
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg> <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>
最近播放 最近播放
</router-link> </router-link>
<router-link to="/local-music"
class="flex items-center gap-3 px-3 py-2 rounded-lg transition-all duration-200 text-content-2 hover:text-content hover:bg-subtle"
active-class="!text-content !bg-muted">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
本地音乐
</router-link>
</div> </div>
</div> </div>
@ -127,7 +133,7 @@
<Transition name="drawer"> <Transition name="drawer">
<div <div
v-if="player.showRoamDrawer" v-if="windowVisible && player.showRoamDrawer"
class="fixed inset-0 z-50 flex flex-col backdrop-blur-xl bg-black/80" class="fixed inset-0 z-50 flex flex-col backdrop-blur-xl bg-black/80"
> >
<div class="h-10 flex items-center justify-between px-4 flex-shrink-0" data-tauri-drag-region> <div class="h-10 flex items-center justify-between px-4 flex-shrink-0" data-tauri-drag-region>
@ -143,9 +149,17 @@
<div class="flex-1 min-h-0 flex px-8 pb-8 gap-0"> <div class="flex-1 min-h-0 flex px-8 pb-8 gap-0">
<div class="w-2/5 flex flex-col items-center justify-center flex-shrink-0"> <div class="w-2/5 flex flex-col items-center justify-center flex-shrink-0">
<img <img
:src="roamSong?.al?.picUrl || roamSong?.album?.picUrl" v-if="roamCoverUrl && !roamCoverError"
:src="roamCoverUrl"
class="w-72 h-72 rounded-3xl object-cover shadow-2xl mb-4" class="w-72 h-72 rounded-3xl object-cover shadow-2xl mb-4"
@error="roamCoverError = true"
/> />
<div
v-else
class="w-72 h-72 rounded-3xl bg-white/10 flex items-center justify-center shadow-2xl mb-4"
>
<svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="text-white/30"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
</div>
<h1 class="text-2xl font-bold text-white text-center">{{ roamSong?.name }}</h1> <h1 class="text-2xl font-bold text-white text-center">{{ roamSong?.name }}</h1>
<p class="text-content-2 mt-2 text-center">{{ roamArtists }}</p> <p class="text-content-2 mt-2 text-center">{{ roamArtists }}</p>
</div> </div>
@ -228,6 +242,7 @@ import { usePlayerStore } from './stores/player';
import { useLyric } from './composables/UserLyric'; import { useLyric } from './composables/UserLyric';
import { getCurrentWindow } from '@tauri-apps/api/window'; import { getCurrentWindow } from '@tauri-apps/api/window';
import { listen } from '@tauri-apps/api/event'; import { listen } from '@tauri-apps/api/event';
import { register, unregister } from '@tauri-apps/plugin-global-shortcut';
const router = useRouter(); const router = useRouter();
const route = useRoute(); const route = useRoute();
@ -242,6 +257,7 @@ const showSubPlaylists = ref(true);
const searchQuery = ref(''); const searchQuery = ref('');
const showCloseModal = ref(false); const showCloseModal = ref(false);
const closeDontAskAgain = ref(false); const closeDontAskAgain = ref(false);
const windowVisible = ref(true);
watch(() => settings.theme, (val) => { watch(() => settings.theme, (val) => {
document.documentElement.setAttribute('data-theme', val); document.documentElement.setAttribute('data-theme', val);
@ -257,6 +273,12 @@ const lyricScrollContainer = ref<HTMLElement | null>(null);
const roamLyricHovering = ref(false); const roamLyricHovering = ref(false);
const roamLyricPadPx = ref(0); const roamLyricPadPx = ref(0);
const roamSong = computed(() => player.currentSong); const roamSong = computed(() => player.currentSong);
const roamCoverError = ref(false);
const roamCoverUrl = computed(() => {
if (!roamSong.value) return '';
return roamSong.value.al?.picUrl || roamSong.value.album?.picUrl || '';
});
watch(roamCoverUrl, () => { roamCoverError.value = false; });
let roamResizeObserver: ResizeObserver | null = null; let roamResizeObserver: ResizeObserver | null = null;
function updateRoamLyricPad() { function updateRoamLyricPad() {
@ -416,14 +438,59 @@ onMounted(() => {
const unlisten3 = listen('tray-prev', () => { const unlisten3 = listen('tray-prev', () => {
player.prev(); player.prev();
}); });
const unlisten4 = listen('window-hidden', () => {
windowVisible.value = false;
});
const unlisten5 = listen('window-shown', () => {
windowVisible.value = true;
});
onBeforeUnmount(() => { onBeforeUnmount(() => {
unlisten1.then(fn => fn()); unlisten1.then(fn => fn());
unlisten2.then(fn => fn()); unlisten2.then(fn => fn());
unlisten3.then(fn => fn()); unlisten3.then(fn => fn());
unlisten4.then(fn => fn());
unlisten5.then(fn => fn());
}); });
}); });
async function registerGlobalShortcuts() {
const globalActions: Record<string, () => void> = {
globalPrev: () => player.prev(),
globalNext: () => player.next(),
globalVolUp: () => player.adjustVolume(5),
globalVolDown: () => player.adjustVolume(-5),
};
for (const [id, action] of Object.entries(globalActions)) {
const key = settings.shortcuts[id]?.key;
if (!key) continue;
try { await unregister(key); } catch {}
try {
await register(key, (event) => {
if (event.state === 'Pressed') action();
});
} catch {}
}
}
watch(() => settings.shortcuts, () => {
registerGlobalShortcuts();
}, { deep: true });
onMounted(() => {
registerGlobalShortcuts();
});
function parseShortcutKey(combo: string): { ctrl: boolean; alt: boolean; shift: boolean; code: string } {
const parts = combo.split('+');
return {
ctrl: parts.includes('Control'),
alt: parts.includes('Alt'),
shift: parts.includes('Shift'),
code: parts.find(p => !['Control', 'Alt', 'Shift'].includes(p)) || '',
};
}
onMounted(() => { onMounted(() => {
function onKeydown(e: KeyboardEvent) { function onKeydown(e: KeyboardEvent) {
const el = e.target as HTMLElement; const el = e.target as HTMLElement;
@ -432,13 +499,25 @@ onMounted(() => {
e.preventDefault(); e.preventDefault();
player.toggle(); player.toggle();
} }
if ((e.ctrlKey || e.metaKey) && e.code === 'ArrowRight') {
const localActions: Record<string, () => void> = {
prev: () => player.prev(),
next: () => player.next(),
volUp: () => player.adjustVolume(5),
volDown: () => player.adjustVolume(-5),
};
for (const [id, action] of Object.entries(localActions)) {
const key = settings.shortcuts[id]?.key;
if (!key) continue;
const parsed = parseShortcutKey(key);
const ctrlMatch = parsed.ctrl ? (e.ctrlKey || e.metaKey) : !e.ctrlKey && !e.metaKey;
const altMatch = parsed.alt ? e.altKey : !e.altKey;
const shiftMatch = parsed.shift ? e.shiftKey : !e.shiftKey;
if (ctrlMatch && altMatch && shiftMatch && e.code === parsed.code) {
e.preventDefault(); e.preventDefault();
player.next(); action();
return;
} }
if ((e.ctrlKey || e.metaKey) && e.code === 'ArrowLeft') {
e.preventDefault();
player.prev();
} }
} }
window.addEventListener('keydown', onKeydown); window.addEventListener('keydown', onKeydown);
@ -460,10 +539,8 @@ onMounted(() => {
.custom-scroll::-webkit-scrollbar { width: 0; display: none; } .custom-scroll::-webkit-scrollbar { width: 0; display: none; }
.roam-lyric-line:hover { .roam-lyric-line:hover {
background: var(--c-subtle); background: var(--c-subtle);
color: var(--c-content) !important;
} }
.roam-lyric-active:hover { .roam-lyric-active:hover {
background: var(--c-subtle) !important; background: var(--c-subtle) !important;
color: var(--c-content) !important;
} }
</style> </style>

View File

@ -14,9 +14,12 @@
<div class="flex items-center px-6 h-16"> <div class="flex items-center px-6 h-16">
<div class="flex items-center gap-3 w-56 min-w-0"> <div class="flex items-center gap-3 w-56 min-w-0">
<img :src="player.currentSong?.al?.picUrl" <div v-if="player.currentSong?.al?.picUrl" class="w-10 h-10 rounded-md overflow-hidden flex-shrink-0 cursor-pointer hover:scale-105 transition-transform" @click="player.toggleRoamDrawer()" title="全屏展示">
class="w-10 h-10 rounded-md object-cover flex-shrink-0 cursor-pointer hover:scale-105 transition-transform" <img :src="player.currentSong.al.picUrl" class="w-full h-full object-cover" />
@click="player.toggleRoamDrawer()" title="全屏展示" /> </div>
<div v-else class="w-10 h-10 rounded-md flex-shrink-0 bg-muted flex items-center justify-center cursor-pointer hover:scale-105 transition-transform" @click="player.toggleRoamDrawer()" title="全屏展示">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-content-3"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
</div>
<div class="min-w-0 flex-1"> <div class="min-w-0 flex-1">
<p class="text-sm font-medium truncate">{{ player.currentSong?.name }}</p> <p class="text-sm font-medium truncate">{{ player.currentSong?.name }}</p>
<p class="text-xs text-content-2 truncate"> <p class="text-xs text-content-2 truncate">
@ -27,6 +30,10 @@
<svg v-if="player.currentSong && player.isLiked(player.currentSong.id)" width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg> <svg v-if="player.currentSong && player.isLiked(player.currentSong.id)" width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg>
<svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg> <svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg>
</button> </button>
<button v-if="player.currentSong && !download.isDownloaded(player.currentSong!.id) && !download.isDownloading(player.currentSong!.id)" @click="download.downloadSong(player.currentSong)" class="flex-shrink-0 text-content-3 hover:text-accent-text transition" title="下载">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
</button>
<svg v-if="player.currentSong && download.isDownloading(player.currentSong!.id)" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="flex-shrink-0 animate-spin text-content-3"><path d="M21 12a9 9 0 11-6.22-8.56"/></svg>
</div> </div>
<div class="flex-1 flex flex-col items-center justify-center gap-1"> <div class="flex-1 flex flex-col items-center justify-center gap-1">
@ -62,11 +69,11 @@
<div class="w-56 flex justify-end items-center gap-2"> <div class="w-56 flex justify-end items-center gap-2">
<div class="flex items-center gap-1"> <div class="flex items-center gap-1">
<button @click="toggleMute" class="text-content-2 hover:text-content transition"> <button @click="toggleMute" class="text-content-2 hover:text-content transition">
<svg v-if="volume === 0" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><line x1="23" y1="9" x2="17" y2="15"/><line x1="17" y1="9" x2="23" y2="15"/></svg> <svg v-if="player.volume === 0" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><line x1="23" y1="9" x2="17" y2="15"/><line x1="17" y1="9" x2="23" y2="15"/></svg>
<svg v-else width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M19.07 4.93a10 10 0 010 14.14M15.54 8.46a5 5 0 010 7.07"/></svg> <svg v-else width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M19.07 4.93a10 10 0 010 14.14M15.54 8.46a5 5 0 010 7.07"/></svg>
</button> </button>
<div class="relative w-20 h-6 flex items-center"> <div class="relative w-20 h-6 flex items-center">
<input ref="volumeSlider" type="range" min="0" max="100" :value="volume" <input ref="volumeSlider" type="range" min="0" max="100" :value="player.volume"
:style="{ background: volumeBarBg }" @input="handleVolumeChange" :style="{ background: volumeBarBg }" @input="handleVolumeChange"
class="vol-slider w-full h-1.5 rounded-full appearance-none cursor-pointer bg-emphasis outline-none" /> class="vol-slider w-full h-1.5 rounded-full appearance-none cursor-pointer bg-emphasis outline-none" />
</div> </div>
@ -120,17 +127,18 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, onBeforeUnmount, onMounted } from 'vue'; import { ref, computed, onBeforeUnmount, onMounted } from 'vue';
import { usePlayerStore, PlayMode } from '../stores/player'; import { usePlayerStore, PlayMode } from '../stores/player';
import { useDownload } from '../composables/useDownload';
import { formatTime } from '../utils/format'; import { formatTime } from '../utils/format';
import { invoke } from '@tauri-apps/api/core'; import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event'; import { listen } from '@tauri-apps/api/event';
const player = usePlayerStore(); const player = usePlayerStore();
const download = useDownload();
const showQueuePanel = ref(false); const showQueuePanel = ref(false);
const progressBar = ref<HTMLElement | null>(null); const progressBar = ref<HTMLElement | null>(null);
const isSeeking = ref(false); const isSeeking = ref(false);
const previewTime = ref(0); const previewTime = ref(0);
const cacheProgress = ref(0); const cacheProgress = ref(0);
const volume = ref(100);
const prevVolume = ref(100); const prevVolume = ref(100);
let unlistenCache: (() => void) | null = null; let unlistenCache: (() => void) | null = null;
@ -154,13 +162,13 @@ function togglePlayMode() {
} }
function toggleMute() { function toggleMute() {
if (volume.value > 0) { if (player.volume > 0) {
prevVolume.value = volume.value; prevVolume.value = player.volume;
volume.value = 0; player.volume = 0;
} else { } else {
volume.value = prevVolume.value || 100; player.volume = prevVolume.value || 100;
} }
invoke('set_volume', { vol: volume.value / 100 }); invoke('set_volume', { vol: player.volume / 100 });
} }
let onDocMove: ((e: MouseEvent) => void) | null = null; let onDocMove: ((e: MouseEvent) => void) | null = null;
@ -221,17 +229,26 @@ function playFromQueue(index: number) {
async function handleVolumeChange(e: Event) { async function handleVolumeChange(e: Event) {
const target = e.target as HTMLInputElement; const target = e.target as HTMLInputElement;
const val = parseInt(target.value, 10); const val = parseInt(target.value, 10);
volume.value = val; player.volume = val;
await invoke('set_volume', { vol: val / 100 }); await invoke('set_volume', { vol: val / 100 });
} }
const volumeBarBg = computed(() => { const volumeBarBg = computed(() => {
const pct = volume.value; const pct = player.volume;
return `linear-gradient(to right, var(--c-accent) 0%, var(--c-accent) ${pct}%, var(--c-muted) ${pct}%)`; return `linear-gradient(to right, var(--c-accent) 0%, var(--c-accent) ${pct}%, var(--c-muted) ${pct}%)`;
}); });
</script> </script>
<style scoped> <style scoped>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.15s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
.slide-up-enter-active, .slide-up-enter-active,
.slide-up-leave-active { .slide-up-leave-active {
transition: all 0.2s ease; transition: all 0.2s ease;

View File

@ -0,0 +1,135 @@
import { reactive, watch } from 'vue';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import { useSettingsStore } from '../stores/settings';
import { showToast } from '../composables/useToast';
interface DownloadTask {
id: number;
name: string;
progress: number;
}
const downloadingIds = reactive<Set<number>>(new Set());
const tasks = reactive<DownloadTask[]>([]);
const localSongIds = reactive<Set<number>>(new Set());
let listenerSetup = false;
let storeSetup = false;
async function setupDownloadListener() {
if (listenerSetup) return;
listenerSetup = true;
await listen<{ id: number; progress: number; name: string }>('download-progress', (event) => {
const { id, progress, name } = event.payload;
if (progress >= 100) {
const idx = tasks.findIndex(t => t.id === id);
if (idx >= 0) {
tasks.splice(idx, 1);
downloadingIds.delete(id);
showToast(`${name} 下载完成`, 'success');
}
} else {
const task = tasks.find(t => t.id === id);
if (task) {
task.progress = progress;
}
}
});
}
async function refreshLocalIds() {
try {
const settings = useSettingsStore();
const list: { id: number }[] = await invoke('list_local_songs', { downloadPath: settings.downloadPath || null });
localSongIds.clear();
for (const s of list) {
localSongIds.add(s.id);
}
} catch {}
}
function ensureStoreSetup() {
if (storeSetup) return;
storeSetup = true;
const settings = useSettingsStore();
refreshLocalIds();
watch(() => settings.downloadPath, () => {
refreshLocalIds();
});
}
function isDownloaded(songId: number): boolean {
return localSongIds.has(songId);
}
function isDownloading(songId: number): boolean {
return downloadingIds.has(songId);
}
function getDownloadProgress(songId: number): number {
const task = tasks.find(t => t.id === songId);
return task?.progress ?? 0;
}
async function downloadSong(song: { id: number; name: string; ar?: { name: string }[]; artists?: { name: string }[]; al?: { picUrl?: string; name?: string }; album?: { picUrl?: string; name?: string }; dt?: number; duration?: number }) {
if (downloadingIds.has(song.id)) return;
if (localSongIds.has(song.id)) {
showToast(`${song.name} 已下载`, 'info');
return;
}
const settings = useSettingsStore();
const artist = song.ar?.map(a => a.name).join(' / ') || song.artists?.map(a => a.name).join(' / ') || '未知';
const albumName = song.al?.name || song.album?.name || null;
const durationVal = song.dt || song.duration || null;
const coverUrl = song.al?.picUrl || song.album?.picUrl || null;
downloadingIds.add(song.id);
tasks.push({ id: song.id, name: song.name, progress: 0 });
try {
await invoke('download_song', {
query: {
id: song.id,
name: song.name,
artist,
album: albumName,
duration: durationVal,
coverUrl,
level: settings.audioQuality,
downloadPath: settings.downloadPath || null,
},
});
localSongIds.add(song.id);
} catch (e: any) {
downloadingIds.delete(song.id);
const idx = tasks.findIndex(t => t.id === song.id);
if (idx >= 0) tasks.splice(idx, 1);
if (e === '文件已存在') {
localSongIds.add(song.id);
showToast(`${song.name} 已下载`, 'info');
} else if (e === 'VIP歌曲无法下载') {
showToast(`${song.name} 为 VIP 歌曲,无法下载`, 'error');
} else if (typeof e === 'string' && e.includes('VIP')) {
showToast(`${song.name} 需要 VIP 权限才能下载`, 'error');
} else {
showToast(`下载失败: ${e}`, 'error');
}
}
}
export function useDownload() {
setupDownloadListener();
ensureStoreSetup();
return {
downloadingIds,
tasks,
localSongIds,
isDownloaded,
isDownloading,
getDownloadProgress,
downloadSong,
refreshLocalIds,
};
}

View File

@ -6,6 +6,7 @@ import Login from '@/views/Login.vue';
import FavoriteSongs from '@/views/FavoriteSongs.vue'; import FavoriteSongs from '@/views/FavoriteSongs.vue';
import RecentPlays from '@/views/RecentPlays.vue'; import RecentPlays from '@/views/RecentPlays.vue';
import DailySongs from '@/views/DailySongs.vue'; import DailySongs from '@/views/DailySongs.vue';
import LocalMusic from '@/views/LocalMusic.vue';
import Settings from '@/views/Settings.vue'; import Settings from '@/views/Settings.vue';
@ -17,6 +18,7 @@ const routes = [
{ path: '/favorites', name: 'favorites', component: FavoriteSongs }, { path: '/favorites', name: 'favorites', component: FavoriteSongs },
{ path: '/recent', name: 'recent', component: RecentPlays }, { path: '/recent', name: 'recent', component: RecentPlays },
{ path: '/daily', name: 'daily', component: DailySongs }, { path: '/daily', name: 'daily', component: DailySongs },
{ path: '/local-music', name: 'local-music', component: LocalMusic },
{ path: '/login', name: 'login', component: Login }, { path: '/login', name: 'login', component: Login },
{ path: '/playlist/:id', name: 'playlist', component: PlaylistDetail }, { path: '/playlist/:id', name: 'playlist', component: PlaylistDetail },
{ path: '/settings', name: 'settings', component: Settings }, { path: '/settings', name: 'settings', component: Settings },

View File

@ -4,6 +4,7 @@ import { invoke } from '@tauri-apps/api/core';
import { normalizeSong } from '../utils/song'; import { normalizeSong } from '../utils/song';
import { useSettingsStore } from './settings'; import { useSettingsStore } from './settings';
import { useUserStore } from './user'; import { useUserStore } from './user';
import { showToast } from '../composables/useToast';
export type PlayMode = 'loop' | 'shuffle' | 'repeat-one'; export type PlayMode = 'loop' | 'shuffle' | 'repeat-one';
@ -11,18 +12,17 @@ export interface Song {
id: number; id: number;
name: string; name: string;
ar: { name: string }[]; ar: { name: string }[];
al: { picUrl: string }; al: { picUrl: string; name?: string };
dt?: number; dt?: number;
// 兼容不同接口返回的可选字段 album?: { picUrl?: string; name?: string };
album?: { picUrl?: string };
artists?: { name: string }[]; artists?: { name: string }[];
duration?: number; // 某些接口的时长字段(单位可能是秒) duration?: number;
localPath?: string;
} }
const cacheProgress = ref(0); const cacheProgress = ref(0);
// 监听 Tauri 事件(需要在适当位置初始化一次)
import { listen } from '@tauri-apps/api/event'; import { listen } from '@tauri-apps/api/event';
export function setupCacheProgressListener() { export function setupCacheProgressListener() {
@ -31,9 +31,6 @@ export function setupCacheProgressListener() {
}); });
} }
// 在 store 定义外调用 setupCacheProgressListener(),或者在应用入口调用
function loadRecentLocal(): Song[] { function loadRecentLocal(): Song[] {
try { try {
const raw = localStorage.getItem('recent_local'); const raw = localStorage.getItem('recent_local');
@ -58,6 +55,7 @@ export const usePlayerStore = defineStore('player', () => {
const queue = ref<Song[]>([]); const queue = ref<Song[]>([]);
const currentIndex = ref(-1); const currentIndex = ref(-1);
const volume = ref(100);
let tickInterval: ReturnType<typeof setInterval> | null = null; let tickInterval: ReturnType<typeof setInterval> | null = null;
@ -124,9 +122,11 @@ export const usePlayerStore = defineStore('player', () => {
fmNextCallback = null; fmNextCallback = null;
} }
// 播放私人漫游歌曲(清空队列,只播放这一首) let fmVipSkipCount = 0;
const MAX_FM_VIP_SKIP = 10;
async function playFmSong(song: any) { async function playFmSong(song: any) {
// 如果缺少时长,尝试从详情接口获取 if (tickInterval) { clearInterval(tickInterval); tickInterval = null; }
if (!song.dt || song.dt === 0) { if (!song.dt || song.dt === 0) {
try { try {
const jsonStr: string = await invoke('get_song_detail', { id: String(song.id) }); const jsonStr: string = await invoke('get_song_detail', { id: String(song.id) });
@ -145,12 +145,36 @@ export const usePlayerStore = defineStore('player', () => {
currentIndex.value = -1; currentIndex.value = -1;
playing.value = false; playing.value = false;
fmSong.value = song;
currentSong.value = song; currentSong.value = song;
try { try {
const settings = useSettingsStore(); const settings = useSettingsStore();
const url: string = await invoke('get_song_url', { query: { id: Number(song.id), level: settings.audioQuality } }); const jsonStr: string = await invoke('get_song_url', { query: { id: Number(song.id), level: settings.audioQuality, fm_mode: true } });
const data = JSON.parse(jsonStr);
const url: string | undefined = data.url;
if (!url) throw new Error('无播放源'); if (!url) throw new Error('无播放源');
if (data.freeTrialInfo) {
console.warn('FM VIP 试听歌曲,自动跳过', song.name);
showToast(`${song.name} 为 VIP 试听,已跳过`, 'info');
fmVipSkipCount++;
if (fmVipSkipCount >= MAX_FM_VIP_SKIP) {
console.warn('FM 连续跳过 VIP 歌曲过多,停止');
fmVipSkipCount = 0;
disableFmMode();
return;
}
if (fmNextCallback) {
fmNextCallback();
} else {
disableFmMode();
}
return;
}
fmVipSkipCount = 0;
await invoke('play_audio', { url }); await invoke('play_audio', { url });
await waitForAudioStart();
playing.value = true; playing.value = true;
duration.value = (song.dt || 0) / 1000; duration.value = (song.dt || 0) / 1000;
currentTime.value = 0; currentTime.value = 0;
@ -159,16 +183,19 @@ export const usePlayerStore = defineStore('player', () => {
} catch (e) { } catch (e) {
console.error('FM播放失败', e); console.error('FM播放失败', e);
playing.value = false; playing.value = false;
if (fmNextCallback) {
fmNextCallback();
} else {
disableFmMode();
}
} }
} }
// 播放指定歌曲(如果不在队列中则加入并切换)
async function play(song: Song) { async function play(song: Song) {
disableFmMode(); disableFmMode();
const idx = queue.value.findIndex(s => s.id === song.id); const idx = queue.value.findIndex(s => s.id === song.id);
if (idx === -1) { if (idx === -1) {
// 未在队列中,添加到队列并播放该位置
queue.value.push(song); queue.value.push(song);
currentIndex.value = queue.value.length - 1; currentIndex.value = queue.value.length - 1;
} else { } else {
@ -177,7 +204,34 @@ export const usePlayerStore = defineStore('player', () => {
await playCurrent(); await playCurrent();
} }
async function playFromList(songs: Song[], startIndex: number) {
disableFmMode();
if (songs.length === 0) return;
queue.value = [...songs];
currentIndex.value = Math.max(0, Math.min(startIndex, songs.length - 1));
await playCurrent();
}
let vipSkipCount = 0;
const MAX_VIP_SKIP = 10;
let audioStartedResolve: (() => void) | null = null;
listen('audio-started', () => {
if (audioStartedResolve) {
audioStartedResolve();
audioStartedResolve = null;
}
});
function waitForAudioStart(): Promise<void> {
return new Promise<void>((resolve) => {
audioStartedResolve = resolve;
});
}
async function playCurrent() { async function playCurrent() {
if (tickInterval) { clearInterval(tickInterval); tickInterval = null; }
const song = queue.value[currentIndex.value]; const song = queue.value[currentIndex.value];
if (!song?.id) { if (!song?.id) {
console.error('无效的歌曲数据', song); console.error('无效的歌曲数据', song);
@ -185,23 +239,49 @@ export const usePlayerStore = defineStore('player', () => {
} }
try { try {
// 重置状态
currentSong.value = song; currentSong.value = song;
playing.value = false; playing.value = false;
currentTime.value = 0; currentTime.value = 0;
duration.value = (song.dt || 0) / 1000; duration.value = (song.dt || song.duration || 0) / 1000;
if (song.localPath) {
await invoke('play_local_audio', { path: song.localPath });
await waitForAudioStart();
playing.value = true;
startTick();
addRecent(song);
return;
}
const settings = useSettingsStore(); const settings = useSettingsStore();
const url: string = await invoke('get_song_url', { query: { id: Number(song.id), level: settings.audioQuality } }); const jsonStr: string = await invoke('get_song_url', { query: { id: Number(song.id), level: settings.audioQuality } });
const data = JSON.parse(jsonStr);
const url: string | undefined = data.url;
if (!url) { if (!url) {
console.error('未获取到有效播放地址', song); console.error('未获取到有效播放地址', song);
return; return;
} }
if (data.freeTrialInfo) {
console.warn('VIP 试听歌曲,自动跳过', song.name);
showToast(`${song.name} 为 VIP 试听,已跳过`, 'info');
vipSkipCount++;
if (vipSkipCount >= MAX_VIP_SKIP) {
console.warn('连续跳过 VIP 歌曲过多,停止跳过');
vipSkipCount = 0;
return;
}
next();
return;
}
await invoke('play_audio', { url }); await invoke('play_audio', { url });
await waitForAudioStart();
playing.value = true; playing.value = true;
startTick(); startTick();
addRecent(song); addRecent(song);
vipSkipCount = 0;
} catch (e) { } catch (e) {
console.error('播放失败', e); console.error('播放失败', e);
playing.value = false; playing.value = false;
@ -215,7 +295,8 @@ export const usePlayerStore = defineStore('player', () => {
currentTime.value += 0.25; currentTime.value += 0.25;
if (currentTime.value >= duration.value) { if (currentTime.value >= duration.value) {
currentTime.value = duration.value; currentTime.value = duration.value;
next(); // 自动下一首 if (tickInterval) { clearInterval(tickInterval); tickInterval = null; }
next();
} }
} }
}, 250); }, 250);
@ -237,7 +318,7 @@ export const usePlayerStore = defineStore('player', () => {
currentSong.value = null; currentSong.value = null;
currentTime.value = 0; currentTime.value = 0;
if (tickInterval) clearInterval(tickInterval); if (tickInterval) clearInterval(tickInterval);
disableFmMode(); // 停止时退出漫游 disableFmMode();
} }
@ -248,7 +329,6 @@ export const usePlayerStore = defineStore('player', () => {
playCurrent(); playCurrent();
} }
// 批量添加歌曲到队列并播放第一首(用于“播放全部”)
async function playAll(songs: Song[]) { async function playAll(songs: Song[]) {
if (songs.length === 0) return; if (songs.length === 0) return;
queue.value = [...songs]; queue.value = [...songs];
@ -260,22 +340,17 @@ export const usePlayerStore = defineStore('player', () => {
if (index < 0 || index >= queue.value.length) return; if (index < 0 || index >= queue.value.length) return;
const isCurrent = index === currentIndex.value; const isCurrent = index === currentIndex.value;
if (isCurrent) { if (isCurrent) {
// 如果移除的是当前正在播放的歌曲,先停止,然后调整索引
stop(); stop();
queue.value.splice(index, 1); queue.value.splice(index, 1);
// 如果队列变空,则重置
if (queue.value.length === 0) { if (queue.value.length === 0) {
currentIndex.value = -1; currentIndex.value = -1;
return; return;
} }
// 保持索引不变,但如果删的是最后一个,索引需要退一位
if (currentIndex.value >= queue.value.length) { if (currentIndex.value >= queue.value.length) {
currentIndex.value = queue.value.length - 1; currentIndex.value = queue.value.length - 1;
} }
// 不自动播放,等用户手动选择
} else { } else {
queue.value.splice(index, 1); queue.value.splice(index, 1);
// 调整当前索引
if (index < currentIndex.value) { if (index < currentIndex.value) {
currentIndex.value -= 1; currentIndex.value -= 1;
} }
@ -297,15 +372,19 @@ export const usePlayerStore = defineStore('player', () => {
} }
} }
async function adjustVolume(delta: number) {
const newVol = Math.max(0, Math.min(100, volume.value + delta));
volume.value = newVol;
await invoke('set_volume', { vol: newVol / 100 });
}
// 在 defineStore 内部添加
const playMode = ref<PlayMode>('loop'); const playMode = ref<PlayMode>('loop');
function setPlayMode(mode: PlayMode) { function setPlayMode(mode: PlayMode) {
playMode.value = mode; playMode.value = mode;
} }
// 重写 next() 以根据模式选择下一首
function next() { function next() {
if (isFmMode.value && fmNextCallback) { if (isFmMode.value && fmNextCallback) {
fmNextCallback(); fmNextCallback();
@ -316,11 +395,9 @@ export const usePlayerStore = defineStore('player', () => {
let nextIndex: number; let nextIndex: number;
switch (playMode.value) { switch (playMode.value) {
case 'repeat-one': case 'repeat-one':
// 单曲循环,不改变索引,只重新播放当前
playCurrent(); playCurrent();
return; return;
case 'shuffle': case 'shuffle':
// 随机下一首,且不与当前重复(除非只剩一首)
if (queue.value.length === 1) { if (queue.value.length === 1) {
nextIndex = 0; nextIndex = 0;
} else { } else {
@ -331,7 +408,6 @@ export const usePlayerStore = defineStore('player', () => {
break; break;
case 'loop': case 'loop':
default: default:
// 顺序循环
nextIndex = (currentIndex.value + 1) % queue.value.length; nextIndex = (currentIndex.value + 1) % queue.value.length;
break; break;
} }
@ -360,7 +436,7 @@ export const usePlayerStore = defineStore('player', () => {
const songs = data.data || data; const songs = data.data || data;
if (songs && songs.length > 0) { if (songs && songs.length > 0) {
const song = normalizeSong(songs[0]); const song = normalizeSong(songs[0]);
enableFmMode(() => loadFirstFmSong()); // 下一首回调 enableFmMode(() => loadFirstFmSong());
await playFmSong(song); await playFmSong(song);
return true; return true;
} }
@ -383,10 +459,9 @@ async function loadFm() {
if (songs && songs.length > 0) { if (songs && songs.length > 0) {
const song = normalizeSong(songs[0]); const song = normalizeSong(songs[0]);
fmSong.value = song; fmSong.value = song;
enableFmMode(nextFm); // 设置下一首回调为 store 内的 nextFm enableFmMode(nextFm);
await playFmSong(song); // 使用 FM 专用播放方法 await playFmSong(song);
fmPlaying.value = true; fmPlaying.value = true;
// showRoamDrawer.value = true; // 自动打开全屏抽屉
} }
} catch (e) { } catch (e) {
console.error('FM加载失败', e); console.error('FM加载失败', e);
@ -396,17 +471,13 @@ async function loadFm() {
async function toggleFm() { async function toggleFm() {
if (!fmSong.value) return; if (!fmSong.value) return;
if (fmPlaying.value) { if (fmPlaying.value) {
// 当前 FM 正在播放,切换暂停/恢复
await toggle(); // 全局暂停/播放
fmPlaying.value = playing.value;
} else {
// FM 处于暂停状态,或者当前被其他歌曲打断
if (currentSong.value?.id === fmSong.value.id) {
// FM 歌曲还是当前歌曲,直接恢复
await toggle(); await toggle();
fmPlaying.value = playing.value; fmPlaying.value = playing.value;
} else { } else {
// 当前播放的是其他歌曲,重新以 FM 模式播放 FM 歌曲 if (currentSong.value?.id === fmSong.value.id) {
await toggle();
fmPlaying.value = playing.value;
} else {
enableFmMode(nextFm); enableFmMode(nextFm);
await playFmSong(fmSong.value); await playFmSong(fmSong.value);
fmPlaying.value = true; fmPlaying.value = true;
@ -415,20 +486,28 @@ async function toggleFm() {
} }
async function nextFm() { async function nextFm() {
await loadFm(); // 加载下一首 FM 歌曲 await loadFm();
} }
// 监听全局播放变化,若用户选择了非 FM 歌曲,自动退出 FM 状态 listen('audio-ended', () => {
if (tickInterval) { clearInterval(tickInterval); tickInterval = null; }
if (isFmMode.value && fmNextCallback) {
fmNextCallback();
return;
}
if (playing.value && !isFmMode.value) {
next();
}
});
watch(currentSong, (newSong) => { watch(currentSong, (newSong) => {
if (isFmMode.value && newSong?.id !== fmSong.value?.id) { if (isFmMode.value && newSong?.id !== fmSong.value?.id) {
fmPlaying.value = false; fmPlaying.value = false;
// 注意:不调用 disableFmMode,因为可能只是临时切歌,但卡片需要知道 FM 已停止 disableFmMode();
disableFmMode(); // 退出 FM 模式,让上一首按钮恢复
} }
}); });
watch(playing, (val) => { watch(playing, (val) => {
// 只有当前正在播放的是 FM 歌曲时,才同步 fmPlaying
if (currentSong.value?.id === fmSong.value?.id) { if (currentSong.value?.id === fmSong.value?.id) {
fmPlaying.value = val; fmPlaying.value = val;
} else { } else {
@ -451,6 +530,7 @@ watch(playing, (val) => {
playFmSong, playFmSong,
setPlayMode, setPlayMode,
play, play,
playFromList,
playAll, playAll,
toggle, toggle,
stop, stop,
@ -458,6 +538,8 @@ watch(playing, (val) => {
next, next,
seek, seek,
playCurrent, playCurrent,
volume,
adjustVolume,
removeFromQueue, removeFromQueue,
clearQueue, clearQueue,

View File

@ -19,23 +19,50 @@ export const closeActionLabels: Record<CloseAction, string> = {
exit: '直接退出', exit: '直接退出',
}; };
export interface ShortcutBinding {
key: string;
label: string;
}
export const defaultShortcuts: Record<string, ShortcutBinding> = {
prev: { key: 'Control+ArrowLeft', label: '上一首' },
next: { key: 'Control+ArrowRight', label: '下一首' },
volUp: { key: 'Control+ArrowUp', label: '音量增加' },
volDown: { key: 'Control+ArrowDown', label: '音量减小' },
globalPrev: { key: 'Alt+Control+ArrowLeft', label: '上一首(全局)' },
globalNext: { key: 'Alt+Control+ArrowRight', label: '下一首(全局)' },
globalVolUp: { key: 'Alt+Control+ArrowUp', label: '音量增加(全局)' },
globalVolDown: { key: 'Alt+Control+ArrowDown', label: '音量减小(全局)' },
};
interface SettingsData { interface SettingsData {
audioQuality: AudioQuality; audioQuality: AudioQuality;
downloadPath: string; downloadPath: string;
theme: ThemeMode; theme: ThemeMode;
closeAction: CloseAction; closeAction: CloseAction;
shortcuts: Record<string, ShortcutBinding>;
} }
function loadSettings(): SettingsData { function loadSettings(): SettingsData {
try { try {
const raw = localStorage.getItem('app_settings'); const raw = localStorage.getItem('app_settings');
if (raw) return JSON.parse(raw); if (raw) {
const parsed = JSON.parse(raw);
return {
audioQuality: parsed.audioQuality || 'standard',
downloadPath: parsed.downloadPath || '',
theme: parsed.theme || 'dark',
closeAction: parsed.closeAction || 'ask',
shortcuts: { ...defaultShortcuts, ...(parsed.shortcuts || {}) },
};
}
} catch {} } catch {}
return { return {
audioQuality: 'standard', audioQuality: 'standard',
downloadPath: '', downloadPath: '',
theme: 'dark', theme: 'dark',
closeAction: 'ask', closeAction: 'ask',
shortcuts: { ...defaultShortcuts },
}; };
} }
@ -46,6 +73,7 @@ export const useSettingsStore = defineStore('settings', () => {
const downloadPath = ref<string>(saved.downloadPath); const downloadPath = ref<string>(saved.downloadPath);
const theme = ref<ThemeMode>(saved.theme); const theme = ref<ThemeMode>(saved.theme);
const closeAction = ref<CloseAction>(saved.closeAction || 'ask'); const closeAction = ref<CloseAction>(saved.closeAction || 'ask');
const shortcuts = ref<Record<string, ShortcutBinding>>(saved.shortcuts);
function setAudioQuality(q: AudioQuality) { function setAudioQuality(q: AudioQuality) {
audioQuality.value = q; audioQuality.value = q;
@ -63,12 +91,29 @@ export const useSettingsStore = defineStore('settings', () => {
closeAction.value = a; closeAction.value = a;
} }
watch([audioQuality, downloadPath, theme, closeAction], () => { function setShortcut(id: string, key: string) {
shortcuts.value = { ...shortcuts.value, [id]: { ...shortcuts.value[id], key } };
}
function resetShortcuts() {
shortcuts.value = { ...defaultShortcuts };
}
function resetAll() {
audioQuality.value = 'standard';
downloadPath.value = '';
theme.value = 'dark';
closeAction.value = 'ask';
shortcuts.value = { ...defaultShortcuts };
}
watch([audioQuality, downloadPath, theme, closeAction, shortcuts], () => {
const data: SettingsData = { const data: SettingsData = {
audioQuality: audioQuality.value, audioQuality: audioQuality.value,
downloadPath: downloadPath.value, downloadPath: downloadPath.value,
theme: theme.value, theme: theme.value,
closeAction: closeAction.value, closeAction: closeAction.value,
shortcuts: shortcuts.value,
}; };
localStorage.setItem('app_settings', JSON.stringify(data)); localStorage.setItem('app_settings', JSON.stringify(data));
}, { deep: true }); }, { deep: true });
@ -78,9 +123,13 @@ export const useSettingsStore = defineStore('settings', () => {
downloadPath, downloadPath,
theme, theme,
closeAction, closeAction,
shortcuts,
setAudioQuality, setAudioQuality,
setDownloadPath, setDownloadPath,
setTheme, setTheme,
setCloseAction, setCloseAction,
setShortcut,
resetShortcuts,
resetAll,
}; };
}); });

View File

@ -3,14 +3,15 @@
*/ */
export function normalizeSong(song: any) { export function normalizeSong(song: any) {
const normalized = { ...song }; const normalized = { ...song };
// 封面 / 艺术家兼容
if (!normalized.al?.picUrl && normalized.album?.picUrl) { if (!normalized.al?.picUrl && normalized.album?.picUrl) {
normalized.al = { ...normalized.al, picUrl: normalized.album.picUrl }; normalized.al = { ...normalized.al, picUrl: normalized.album.picUrl };
} }
if (!normalized.al?.name && normalized.album?.name) {
normalized.al = { ...normalized.al, name: normalized.album.name };
}
if (!normalized.ar || normalized.ar.length === 0) { if (!normalized.ar || normalized.ar.length === 0) {
normalized.ar = normalized.artists || []; normalized.ar = normalized.artists || [];
} }
// 时长:只保留合理的 dt100ms ~ 2小时否则置 0
if (!normalized.dt || normalized.dt < 100 || normalized.dt > 7200000) { if (!normalized.dt || normalized.dt < 100 || normalized.dt > 7200000) {
normalized.dt = 0; normalized.dt = 0;
} }

View File

@ -18,7 +18,7 @@
<div <div
v-for="(song, index) in songs" v-for="(song, index) in songs"
:key="song.id" :key="song.id"
@click="player.play(song)" @click="player.playFromList(songs, index)"
class="flex items-center gap-4 p-3 rounded-xl hover:bg-subtle transition cursor-pointer group" class="flex items-center gap-4 p-3 rounded-xl hover:bg-subtle transition cursor-pointer group"
:class="{ 'bg-accent-dim': isCurrentSong(song.id) }" :class="{ 'bg-accent-dim': isCurrentSong(song.id) }"
> >
@ -46,6 +46,11 @@
<svg v-if="player.isLiked(song.id)" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" class="text-danger"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg> <svg v-if="player.isLiked(song.id)" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" class="text-danger"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg>
<svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg> <svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg>
</button> </button>
<button @click.stop="download.downloadSong(song)" class="text-content-3 hover:text-accent-text transition flex-shrink-0" :title="download.isDownloaded(song.id) ? '已下载' : '下载'">
<svg v-if="download.isDownloading(song.id)" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="animate-spin"><path d="M21 12a9 9 0 11-6.22-8.56"/></svg>
<svg v-else-if="download.isDownloaded(song.id)" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-accent-text"><polyline points="20 6 9 17 4 12"/></svg>
<svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
</button>
<span class="text-xs text-content-3">{{ formatDuration(song.dt) }}</span> <span class="text-xs text-content-3">{{ formatDuration(song.dt) }}</span>
</div> </div>
</div> </div>
@ -56,9 +61,11 @@
import { ref, onMounted } from 'vue'; import { ref, onMounted } from 'vue';
import { invoke } from '@tauri-apps/api/core'; import { invoke } from '@tauri-apps/api/core';
import { usePlayerStore } from '../stores/player'; import { usePlayerStore } from '../stores/player';
import { useDownload } from '../composables/useDownload';
import { formatDuration } from '../utils/format'; import { formatDuration } from '../utils/format';
const player = usePlayerStore(); const player = usePlayerStore();
const download = useDownload();
const songs = ref<any[]>([]); const songs = ref<any[]>([]);
const loading = ref(true); const loading = ref(true);

View File

@ -38,18 +38,23 @@
<div v-if="loading" class="text-content-2">搜索中...</div> <div v-if="loading" class="text-content-2">搜索中...</div>
<div v-else class="space-y-3"> <div v-else class="space-y-3">
<div <div
v-for="song in results" v-for="(song, index) in results"
:key="song.id" :key="song.id"
@click="playSong(song)" @click="playSong(song, index)"
class="flex items-center gap-4 p-3 rounded-xl backdrop-blur-md bg-subtle hover:bg-muted border border-line-2 cursor-pointer transition" class="flex items-center gap-4 p-3 rounded-xl backdrop-blur-md bg-subtle hover:bg-muted border border-line-2 cursor-pointer transition"
> >
<img :src="song.al?.picUrl" class="w-12 h-12 rounded-lg object-cover" /> <img :src="song.al?.picUrl" class="w-12 h-12 rounded-lg object-cover" />
<div> <div class="flex-1 min-w-0">
<p class="font-medium">{{ song.name }}</p> <p class="font-medium truncate">{{ song.name }}</p>
<p class="text-sm text-content-2"> <p class="text-sm text-content-2 truncate">
{{ song.ar?.map((a: any) => a.name).join(' / ') }} {{ song.ar?.map((a: any) => a.name).join(' / ') }}
</p> </p>
</div> </div>
<button @click.stop="download.downloadSong(song)" class="text-content-3 hover:text-accent-text transition flex-shrink-0" :title="download.isDownloaded(song.id) ? '已下载' : '下载'">
<svg v-if="download.isDownloading(song.id)" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="animate-spin"><path d="M21 12a9 9 0 11-6.22-8.56"/></svg>
<svg v-else-if="download.isDownloaded(song.id)" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-accent-text"><polyline points="20 6 9 17 4 12"/></svg>
<svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
</button>
</div> </div>
<p v-if="!loading && hasSearched && results.length === 0" class="text-content-2">无结果</p> <p v-if="!loading && hasSearched && results.length === 0" class="text-content-2">无结果</p>
</div> </div>
@ -63,10 +68,12 @@ import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router'; import { useRouter, useRoute } from 'vue-router';
import { invoke } from '@tauri-apps/api/core'; import { invoke } from '@tauri-apps/api/core';
import { usePlayerStore } from '../stores/player'; import { usePlayerStore } from '../stores/player';
import { useDownload } from '../composables/useDownload';
const router = useRouter(); const router = useRouter();
const route = useRoute(); const route = useRoute();
const player = usePlayerStore(); const player = usePlayerStore();
const download = useDownload();
const keyword = ref(''); const keyword = ref('');
const results = ref<any[]>([]); const results = ref<any[]>([]);
@ -116,8 +123,15 @@ function searchTag(tag: string) {
handleSearch(); handleSearch();
} }
async function playSong(song: any) { async function playSong(_song: any, index: number) {
player.play(song); const normalized = results.value.map((s: any) => ({
id: s.id,
name: s.name,
ar: s.ar || s.artists || [],
al: s.al || s.album || { picUrl: '' },
dt: s.dt || 0,
}));
player.playFromList(normalized, index);
} }
</script> </script>

View File

@ -22,7 +22,7 @@
<div <div
v-for="(song, index) in songs" v-for="(song, index) in songs"
:key="song.id" :key="song.id"
@click="player.play(song)" @click="player.playFromList(songs, index)"
class="flex items-center gap-4 p-3 rounded-xl hover:bg-subtle transition cursor-pointer" class="flex items-center gap-4 p-3 rounded-xl hover:bg-subtle transition cursor-pointer"
> >
<span class="text-xs text-content-3 w-6 text-right">{{ index + 1 }}</span> <span class="text-xs text-content-3 w-6 text-right">{{ index + 1 }}</span>
@ -37,6 +37,11 @@
<svg v-if="player.isLiked(song.id)" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" class="text-danger"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg> <svg v-if="player.isLiked(song.id)" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" class="text-danger"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg>
<svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg> <svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg>
</button> </button>
<button @click.stop="download.downloadSong(song)" class="text-content-3 hover:text-accent-text transition flex-shrink-0" :title="download.isDownloaded(song.id) ? '已下载' : '下载'">
<svg v-if="download.isDownloading(song.id)" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="animate-spin"><path d="M21 12a9 9 0 11-6.22-8.56"/></svg>
<svg v-else-if="download.isDownloaded(song.id)" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-accent-text"><polyline points="20 6 9 17 4 12"/></svg>
<svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
</button>
<span class="text-xs text-content-3">{{ formatDuration(song.dt) }}</span> <span class="text-xs text-content-3">{{ formatDuration(song.dt) }}</span>
</div> </div>
</div> </div>
@ -48,11 +53,13 @@ import { ref, onMounted } from 'vue';
import { invoke } from '@tauri-apps/api/core'; import { invoke } from '@tauri-apps/api/core';
import { usePlayerStore } from '../stores/player'; import { usePlayerStore } from '../stores/player';
import { useUserStore } from '../stores/user'; import { useUserStore } from '../stores/user';
import { useDownload } from '../composables/useDownload';
import { normalizeSong } from '../utils/song'; import { normalizeSong } from '../utils/song';
import { formatDuration } from '../utils/format'; import { formatDuration } from '../utils/format';
const player = usePlayerStore(); const player = usePlayerStore();
const userStore = useUserStore(); const userStore = useUserStore();
const download = useDownload();
const songs = ref<any[]>([]); const songs = ref<any[]>([]);
const loading = ref(true); const loading = ref(true);

225
src/views/LocalMusic.vue Normal file
View File

@ -0,0 +1,225 @@
<template>
<div class="p-8 text-content">
<button @click="$router.back()" class="mb-4 text-content-2 hover:text-content transition">
返回
</button>
<div class="flex items-center gap-4 mb-6">
<h1 class="text-2xl font-bold">本地音乐</h1>
<span v-if="songs.length" class="text-xs text-content-3">{{ songs.length }} </span>
<button
v-if="songs.length"
@click="refresh"
class="px-3 py-1 bg-muted hover:bg-emphasis rounded-full text-xs transition"
>
刷新
</button>
</div>
<div v-if="loading" class="text-content-2">加载中...</div>
<div v-else-if="songs.length === 0" class="text-content-3">
当前文件夹下没有音乐文件支持 mp3flacwavoggaacm4a 格式
</div>
<div v-else class="space-y-2">
<div
v-for="(song, index) in songs"
:key="song.id + '-' + index"
@click="playLocalSong(song, index)"
class="flex items-center gap-4 p-3 rounded-xl hover:bg-subtle transition cursor-pointer"
:class="{ 'bg-subtle': player.currentSong?.id === song.id }"
>
<span class="text-xs text-content-3 w-6 text-right flex-shrink-0">{{ index + 1 }}</span>
<div class="w-10 h-10 rounded-lg overflow-hidden flex-shrink-0 bg-muted">
<img v-if="song.cover" :src="song.cover" class="w-full h-full object-cover" />
<div v-else class="w-full h-full flex items-center justify-center">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-content-3"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
</div>
</div>
<div class="flex-1 min-w-0">
<p class="text-sm font-medium truncate">{{ song.name }}</p>
<p class="text-xs text-content-2 truncate">
{{ song.artist }}<template v-if="song.album"> · {{ song.album }}</template>
</p>
</div>
<span class="text-xs text-content-3 flex-shrink-0">{{ formatDuration(song.duration) }}</span>
<span class="text-xs text-content-3 flex-shrink-0">{{ formatFileSize(song.fileSize) }}</span>
<div class="relative flex-shrink-0">
<button
@click.stop="toggleMenu(song.id)"
class="text-content-3 hover:text-content transition p-1 rounded hover:bg-muted"
title="更多"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><circle cx="5" cy="12" r="1.5"/><circle cx="12" cy="12" r="1.5"/><circle cx="19" cy="12" r="1.5"/></svg>
</button>
<Transition name="fade">
<div v-if="openMenuId === song.id" class="absolute right-0 top-full mt-1 w-44 bg-surface border border-line rounded-xl shadow-2xl overflow-hidden z-50" @click.stop>
<button @click="confirmDelete(song)" class="w-full flex items-center gap-2.5 px-4 py-2.5 text-sm text-danger/80 hover:bg-danger/10 transition">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/></svg>
从磁盘中删除
</button>
</div>
</Transition>
</div>
</div>
</div>
<Transition name="fade">
<div v-if="showDeleteConfirm" class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm" @click.self="showDeleteConfirm = false">
<div class="bg-surface border border-line rounded-2xl shadow-2xl w-80 p-6 select-auto">
<h2 class="text-lg font-semibold text-content mb-1">确认删除</h2>
<p class="text-sm text-content-2 mb-5">确定要删除{{ deleteTarget?.name }}此操作不可撤销</p>
<div class="flex gap-3">
<button @click="showDeleteConfirm = false"
class="flex-1 py-2 rounded-lg bg-muted hover:bg-emphasis text-sm text-content-2 transition">
取消
</button>
<button @click="doDelete"
class="flex-1 py-2 rounded-lg bg-danger/20 hover:bg-danger/30 text-danger text-sm font-medium transition">
删除
</button>
</div>
</div>
</div>
</Transition>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { invoke } from '@tauri-apps/api/core';
import { usePlayerStore, type Song } from '../stores/player';
import { useDownload } from '../composables/useDownload';
import { useSettingsStore } from '../stores/settings';
import { showToast } from '../composables/useToast';
const player = usePlayerStore();
const download = useDownload();
const settings = useSettingsStore();
interface LocalSong {
id: number;
name: string;
artist: string;
album: string;
duration: number;
cover: string | null;
filename: string;
fileSize: number;
path: string;
local: boolean;
}
const songs = ref<LocalSong[]>([]);
const loading = ref(true);
const showDeleteConfirm = ref(false);
const deleteTarget = ref<LocalSong | null>(null);
const openMenuId = ref<number | null>(null);
function toggleMenu(id: number) {
openMenuId.value = openMenuId.value === id ? null : id;
}
function closeMenu() {
openMenuId.value = null;
}
onMounted(() => { document.addEventListener('click', closeMenu); });
onBeforeUnmount(() => { document.removeEventListener('click', closeMenu); });
async function refresh() {
loading.value = true;
try {
const list = await invoke<LocalSong[]>('list_local_songs', { downloadPath: settings.downloadPath || null });
songs.value = list;
fetchMissingCovers();
} catch (e) {
console.error(e);
} finally {
loading.value = false;
}
}
async function fetchMissingCovers() {
const missing = songs.value.filter(s => !s.cover && s.id > 0 && s.id < 1e12);
if (missing.length === 0) return;
const ids = [...new Set(missing.map(s => s.id))];
try {
const jsonStr: string = await invoke('get_song_detail', { id: JSON.stringify(ids) });
const data = JSON.parse(jsonStr);
const detailMap = new Map<number, string>();
for (const s of data.songs || []) {
const url = s.al?.picUrl;
if (url && s.id) detailMap.set(s.id, url + '?param=100y100');
}
for (const song of missing) {
const url = detailMap.get(song.id);
if (url) song.cover = url;
}
} catch {}
}
onMounted(refresh);
function formatFileSize(bytes: number): string {
if (bytes === 0) return '0 B';
const units = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(1024));
return (bytes / Math.pow(1024, i)).toFixed(i > 0 ? 1 : 0) + ' ' + units[i];
}
function formatDuration(ms: number): string {
if (!ms || ms === 0) return '--:--';
const totalSec = Math.floor(ms / 1000);
const min = Math.floor(totalSec / 60);
const sec = totalSec % 60;
return `${min}:${sec.toString().padStart(2, '0')}`;
}
function toSong(local: LocalSong): Song {
return {
id: local.id,
name: local.name,
ar: local.artist ? [{ name: local.artist }] : [],
al: { picUrl: local.cover || '', name: local.album || undefined },
dt: local.duration || undefined,
artists: local.artist ? [{ name: local.artist }] : [],
album: { picUrl: local.cover || undefined, name: local.album || undefined },
duration: local.duration || undefined,
localPath: local.path,
};
}
async function playLocalSong(_song: LocalSong, index: number) {
const normalized = songs.value.map(s => toSong(s));
player.playFromList(normalized, index);
}
function confirmDelete(song: LocalSong) {
openMenuId.value = null;
deleteTarget.value = song;
showDeleteConfirm.value = true;
}
async function doDelete() {
if (!deleteTarget.value) return;
try {
await invoke('delete_local_song', { query: { id: deleteTarget.value.id, filename: deleteTarget.value.filename, downloadPath: settings.downloadPath || null } });
songs.value = songs.value.filter(s => s.id !== deleteTarget.value!.id);
download.localSongIds.delete(deleteTarget.value.id);
showToast('已删除', 'success');
} catch (e) {
showToast('删除失败', 'error');
}
showDeleteConfirm.value = false;
deleteTarget.value = null;
}
</script>
<style scoped>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.15s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
</style>

View File

@ -76,6 +76,11 @@
<svg v-if="player.isLiked(song.id)" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" class="text-danger"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg> <svg v-if="player.isLiked(song.id)" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" class="text-danger"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg>
<svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg> <svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg>
</button> </button>
<button @click.stop="download.downloadSong(song)" class="text-content-3 hover:text-accent-text transition flex-shrink-0" :title="download.isDownloaded(song.id) ? '已下载' : '下载'">
<svg v-if="download.isDownloading(song.id)" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="animate-spin"><path d="M21 12a9 9 0 11-6.22-8.56"/></svg>
<svg v-else-if="download.isDownloaded(song.id)" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-accent-text"><polyline points="20 6 9 17 4 12"/></svg>
<svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
</button>
<span class="text-xs text-content-3">{{ formatDuration(song.dt) }}</span> <span class="text-xs text-content-3">{{ formatDuration(song.dt) }}</span>
</div> </div>
</div> </div>
@ -88,12 +93,14 @@ import { useRoute } from 'vue-router';
import { invoke } from '@tauri-apps/api/core'; import { invoke } from '@tauri-apps/api/core';
import { usePlayerStore } from '../stores/player'; import { usePlayerStore } from '../stores/player';
import { useUserStore } from '../stores/user'; import { useUserStore } from '../stores/user';
import { useDownload } from '../composables/useDownload';
import { showToast } from '../composables/useToast'; import { showToast } from '../composables/useToast';
import { formatDuration, formatPlayCount } from '../utils/format'; import { formatDuration, formatPlayCount } from '../utils/format';
const route = useRoute(); const route = useRoute();
const player = usePlayerStore(); const player = usePlayerStore();
const userStore = useUserStore(); const userStore = useUserStore();
const download = useDownload();
const playlist = ref<any>(null); const playlist = ref<any>(null);
const songs = ref<any[]>([]); const songs = ref<any[]>([]);
@ -136,7 +143,8 @@ function isCurrentSong(songId: number): boolean {
} }
async function playSingle(song: any) { async function playSingle(song: any) {
player.play(song); const idx = songs.value.findIndex((s: any) => s.id === song.id);
player.playFromList(songs.value, idx >= 0 ? idx : 0);
} }
function playAll() { function playAll() {

View File

@ -9,7 +9,7 @@
<div <div
v-for="(song, index) in player.recentLocal" v-for="(song, index) in player.recentLocal"
:key="song.id" :key="song.id"
@click="player.play(song)" @click="player.playFromList(player.recentLocal, index)"
class="flex items-center gap-4 p-3 rounded-xl hover:bg-subtle transition cursor-pointer" class="flex items-center gap-4 p-3 rounded-xl hover:bg-subtle transition cursor-pointer"
> >
<span class="text-xs text-content-3 w-6 text-right">{{ index + 1 }}</span> <span class="text-xs text-content-3 w-6 text-right">{{ index + 1 }}</span>
@ -24,6 +24,11 @@
<svg v-if="player.isLiked(song.id)" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" class="text-danger"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg> <svg v-if="player.isLiked(song.id)" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" class="text-danger"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg>
<svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg> <svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg>
</button> </button>
<button @click.stop="download.downloadSong(song)" class="text-content-3 hover:text-accent-text transition flex-shrink-0" :title="download.isDownloaded(song.id) ? '已下载' : '下载'">
<svg v-if="download.isDownloading(song.id)" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="animate-spin"><path d="M21 12a9 9 0 11-6.22-8.56"/></svg>
<svg v-else-if="download.isDownloaded(song.id)" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-accent-text"><polyline points="20 6 9 17 4 12"/></svg>
<svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
</button>
<span class="text-xs text-content-3">{{ formatDuration(song.dt ?? 0) }}</span> <span class="text-xs text-content-3">{{ formatDuration(song.dt ?? 0) }}</span>
</div> </div>
</div> </div>
@ -32,7 +37,9 @@
<script setup lang="ts"> <script setup lang="ts">
import { usePlayerStore } from '../stores/player'; import { usePlayerStore } from '../stores/player';
import { useDownload } from '../composables/useDownload';
import { formatDuration } from '../utils/format'; import { formatDuration } from '../utils/format';
const player = usePlayerStore(); const player = usePlayerStore();
const download = useDownload();
</script> </script>

View File

@ -12,9 +12,17 @@
<template v-else> <template v-else>
<img <img
:src="currentSong.al?.picUrl || currentSong.album?.picUrl" v-if="coverUrl && !coverError"
:src="coverUrl"
class="w-80 h-80 rounded-3xl object-cover shadow-2xl mb-8" class="w-80 h-80 rounded-3xl object-cover shadow-2xl mb-8"
@error="coverError = true"
/> />
<div
v-else
class="w-80 h-80 rounded-3xl bg-muted flex items-center justify-center shadow-2xl mb-8"
>
<svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="text-content-3"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
</div>
<h1 class="text-3xl font-bold mb-2">{{ currentSong.name }}</h1> <h1 class="text-3xl font-bold mb-2">{{ currentSong.name }}</h1>
<p class="text-lg text-content-2 mb-8"> <p class="text-lg text-content-2 mb-8">
@ -46,12 +54,13 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted } from 'vue'; import { ref, computed, watch, onMounted } from 'vue';
import { usePlayerStore } from '../stores/player'; import { usePlayerStore } from '../stores/player';
import { invoke } from '@tauri-apps/api/core'; import { invoke } from '@tauri-apps/api/core';
import { normalizeSong } from '../utils/song'; import { normalizeSong } from '../utils/song';
const player = usePlayerStore(); const player = usePlayerStore();
const coverError = ref(false);
const currentSong = computed(() => { const currentSong = computed(() => {
if (player.isFmMode && player.currentSong) { if (player.isFmMode && player.currentSong) {
@ -60,6 +69,13 @@ const currentSong = computed(() => {
return null; return null;
}); });
const coverUrl = computed(() => {
if (!currentSong.value) return '';
return currentSong.value.al?.picUrl || currentSong.value.album?.picUrl || '';
});
watch(coverUrl, () => { coverError.value = false; });
const artists = computed(() => { const artists = computed(() => {
if (!currentSong.value) return ''; if (!currentSong.value) return '';
return currentSong.value.ar?.map((a: any) => a.name).join(' / ') || return currentSong.value.ar?.map((a: any) => a.name).join(' / ') ||

View File

@ -12,18 +12,23 @@
<div v-if="loading" class="text-content-2">搜索中...</div> <div v-if="loading" class="text-content-2">搜索中...</div>
<div v-else class="space-y-3"> <div v-else class="space-y-3">
<div <div
v-for="song in results" v-for="(song, index) in results"
:key="song.id" :key="song.id"
@click="playSong(song)" @click="playSong(song, index)"
class="flex items-center gap-4 p-3 rounded-xl backdrop-blur-md bg-subtle hover:bg-muted border border-line-2 cursor-pointer transition-all duration-200 hover:scale-[1.01] active:scale-95" class="flex items-center gap-4 p-3 rounded-xl backdrop-blur-md bg-subtle hover:bg-muted border border-line-2 cursor-pointer transition-all duration-200 hover:scale-[1.01] active:scale-95"
> >
<img :src="song.al?.picUrl" class="w-12 h-12 rounded-lg object-cover" /> <img :src="song.al?.picUrl" class="w-12 h-12 rounded-lg object-cover" />
<div> <div class="flex-1 min-w-0">
<p class="font-medium">{{ song.name }}</p> <p class="font-medium truncate">{{ song.name }}</p>
<p class="text-sm text-content-2"> <p class="text-sm text-content-2 truncate">
{{ song.ar?.map((a: any) => a.name).join(' / ') }} {{ song.ar?.map((a: any) => a.name).join(' / ') }}
</p> </p>
</div> </div>
<button @click.stop="download.downloadSong(song)" class="text-content-3 hover:text-accent-text transition flex-shrink-0" :title="download.isDownloaded(song.id) ? '已下载' : '下载'">
<svg v-if="download.isDownloading(song.id)" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="animate-spin"><path d="M21 12a9 9 0 11-6.22-8.56"/></svg>
<svg v-else-if="download.isDownloaded(song.id)" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-accent-text"><polyline points="20 6 9 17 4 12"/></svg>
<svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
</button>
</div> </div>
<p v-if="!loading && hasSearched && results.length === 0" class="text-content-2">无结果</p> <p v-if="!loading && hasSearched && results.length === 0" class="text-content-2">无结果</p>
</div> </div>
@ -39,6 +44,7 @@ import { watch } from 'vue';
import { ref, onMounted } from 'vue'; import { ref, onMounted } from 'vue';
import { invoke } from '@tauri-apps/api/core'; import { invoke } from '@tauri-apps/api/core';
import { usePlayerStore } from '../stores/player'; import { usePlayerStore } from '../stores/player';
import { useDownload } from '../composables/useDownload';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
const router = useRouter(); const router = useRouter();
@ -47,6 +53,7 @@ const results = ref<any[]>([]);
const loading = ref(false); const loading = ref(false);
const hasSearched = ref(false); const hasSearched = ref(false);
const player = usePlayerStore(); const player = usePlayerStore();
const download = useDownload();
const route = useRoute(); const route = useRoute();
watch( watch(
@ -76,9 +83,16 @@ async function handleSearch() {
} }
} }
async function playSong(song: any) { async function playSong(_song: any, index: number) {
try { try {
await player.play(song); const normalized = results.value.map((s: any) => ({
id: s.id,
name: s.name,
ar: s.ar || s.artists || [],
al: s.al || s.album || { picUrl: '' },
dt: s.dt || 0,
}));
await player.playFromList(normalized, index);
} catch (e) { } catch (e) {
alert('暂无播放源或需登录'); alert('暂无播放源或需登录');
} }

View File

@ -64,24 +64,85 @@
<p class="text-xs text-content-3 mt-0.5">歌曲下载保存位置</p> <p class="text-xs text-content-3 mt-0.5">歌曲下载保存位置</p>
</div> </div>
</div> </div>
<div class="flex gap-2"> <div class="flex gap-2 items-center">
<input <div class="flex-1 bg-subtle border border-line rounded-lg px-3 py-2 text-sm text-content-2 truncate" :title="settings.downloadPath || defaultDownloadPath">
v-model="downloadPathInput" {{ settings.downloadPath || defaultDownloadPath }}
type="text" </div>
placeholder="例如:~/Music/Nekosonic"
class="flex-1 bg-subtle border border-line rounded-lg px-3 py-2 text-sm text-content placeholder-content-4 outline-none focus:border-accent/50 transition"
/>
<button <button
@click="saveDownloadPath" @click="pickDownloadFolder"
class="px-4 py-2 bg-accent-dim hover:bg-accent-dim text-accent-text rounded-lg text-sm transition" class="px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 bg-accent/15 text-accent-text hover:bg-accent/25 active:scale-95"
> >
保存 选择文件夹
</button>
<button
v-if="settings.downloadPath"
@click="clearDownloadPath"
class="px-3 py-2 rounded-lg text-sm font-medium transition-all duration-200 bg-muted text-content-2 hover:bg-emphasis hover:text-content active:scale-95"
title="重置为默认路径"
>
重置
</button> </button>
</div> </div>
</div> </div>
</div> </div>
</section> </section>
<section class="mb-8">
<h2 class="text-sm text-content-2 uppercase tracking-wider mb-4">快捷键</h2>
<div class="space-y-3">
<div
v-for="(sc, id) in settings.shortcuts"
:key="id"
class="flex items-center justify-between p-3 bg-subtle rounded-xl"
>
<div>
<p class="text-sm font-medium">{{ sc.label }}</p>
</div>
<div class="flex items-center gap-1.5">
<button
v-if="sc.key !== defaultShortcuts[id]?.key"
@click="settings.setShortcut(id, defaultShortcuts[id].key)"
class="w-6 h-6 flex items-center justify-center rounded-md text-content-4 hover:text-danger hover:bg-danger/10 transition"
title="恢复默认"
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
</button>
<button
@click="startRecording(id)"
class="px-3 py-1.5 rounded-lg text-sm transition min-w-[120px] text-center"
:class="recordingId === id ? 'bg-accent text-white' : 'bg-muted hover:bg-emphasis text-content-2'"
>
{{ recordingId === id ? '按下新快捷键...' : formatShortcut(sc.key) }}
</button>
</div>
</div>
<button
@click="resetShortcuts"
class="text-xs text-content-3 hover:text-danger transition"
>
恢复默认快捷键
</button>
</div>
</section>
<section class="mb-8">
<h2 class="text-sm text-content-2 uppercase tracking-wider mb-4">其他</h2>
<div class="space-y-3">
<div class="flex items-center justify-between p-3 bg-subtle rounded-xl">
<div>
<p class="text-sm font-medium">恢复默认设置</p>
<p class="text-xs text-content-3 mt-0.5">重置所有设置为初始状态</p>
</div>
<button
@click="handleResetAll"
class="px-3 py-1.5 rounded-lg text-sm bg-muted hover:bg-emphasis text-danger transition"
>
重置
</button>
</div>
</div>
</section>
<section class="mb-8"> <section class="mb-8">
<h2 class="text-sm text-content-2 uppercase tracking-wider mb-4">关于</h2> <h2 class="text-sm text-content-2 uppercase tracking-wider mb-4">关于</h2>
<div class="space-y-4"> <div class="space-y-4">
@ -101,30 +162,84 @@
:disabled="checkingUpdate" :disabled="checkingUpdate"
class="flex items-center gap-2 px-4 py-2 bg-subtle hover:bg-muted rounded-lg text-sm transition" class="flex items-center gap-2 px-4 py-2 bg-subtle hover:bg-muted rounded-lg text-sm transition"
> >
<svg v-if="!checkingUpdate" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.66 0 3-4.03 3-9s-1.34-9-3-9m0 18c-1.66 0-3-4.03-3-9s1.34-9 3-9m-9 9a9 9 0 019-9"/></svg> <svg v-if="!checkingUpdate" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>
<svg v-else class="animate-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 11-6.22-8.56"/></svg> <svg v-else class="animate-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 11-6.22-8.56"/></svg>
{{ checkingUpdate ? '检查中...' : '检查更新(暂未实现)' }} {{ checkingUpdate ? '获取中...' : '查看最新版日志' }}
</button> </button>
<p v-if="updateMessage" class="text-xs" :class="updateMessageClass">{{ updateMessage }}</p> <p v-if="updateMessage && !latestRelease" class="text-xs" :class="updateMessageClass">{{ updateMessage }}</p>
</div> </div>
</section> </section>
<Transition name="fade">
<div v-if="showResetConfirm" class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm" @click.self="showResetConfirm = false">
<div class="bg-surface border border-line rounded-2xl shadow-2xl w-80 p-6 select-auto">
<h2 class="text-lg font-semibold text-content mb-1">确认重置</h2>
<p class="text-sm text-content-2 mb-5">所有设置将恢复为默认值此操作不可撤销</p>
<div class="flex gap-3">
<button @click="showResetConfirm = false"
class="flex-1 py-2 rounded-lg bg-muted hover:bg-emphasis text-sm text-content-2 transition">
取消
</button>
<button @click="confirmResetAll"
class="flex-1 py-2 rounded-lg bg-danger/20 hover:bg-danger/30 text-danger text-sm font-medium transition">
确认重置
</button>
</div>
</div>
</div>
</Transition>
<Transition name="fade">
<div v-if="showUpdateModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm" @click.self="showUpdateModal = false">
<div class="bg-surface border border-line rounded-2xl shadow-2xl w-[420px] max-h-[80vh] flex flex-col select-auto">
<div class="p-6 pb-4">
<div class="flex items-center justify-between mb-1">
<h2 class="text-lg font-semibold text-content">最新版本日志</h2>
<span v-if="latestRelease" class="text-xs font-medium px-2 py-0.5 rounded-full bg-accent/15 text-accent-text">v{{ latestRelease.tag_name?.replace('v', '') }}</span>
</div>
<p v-if="latestRelease?.published_at" class="text-xs text-content-3 mt-1">{{ formatDate(latestRelease.published_at) }}</p>
</div>
<div v-if="latestRelease?.body" class="px-6 pb-4 flex-1 overflow-y-auto max-h-60">
<div class="text-sm text-content-2 leading-relaxed whitespace-pre-wrap">{{ latestRelease.body }}</div>
</div>
<div v-else class="px-6 pb-4">
<p class="text-sm text-content-3">暂无更新日志</p>
</div>
<div class="p-4 border-t border-line flex gap-3">
<button @click="showUpdateModal = false"
class="flex-1 py-2 rounded-lg bg-muted hover:bg-emphasis text-sm text-content-2 transition">
关闭
</button>
<button v-if="latestRelease?.html_url" @click="openUrl(latestRelease.html_url)"
class="flex-1 py-2 rounded-lg bg-accent/20 hover:bg-accent/30 text-accent-text text-sm font-medium transition">
Gitea 中查看
</button>
</div>
</div>
</div>
</Transition>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, onMounted } from 'vue'; import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { useSettingsStore, qualityLabels, closeActionLabels, type CloseAction } from '../stores/settings'; import { useSettingsStore, qualityLabels, closeActionLabels, defaultShortcuts, type CloseAction } from '../stores/settings';
import { useToast } from '../composables/useToast'; import { useToast } from '../composables/useToast';
import { invoke } from '@tauri-apps/api/core';
import { getVersion } from '@tauri-apps/api/app'; import { getVersion } from '@tauri-apps/api/app';
import { openUrl } from '@tauri-apps/plugin-opener'; import { openUrl } from '@tauri-apps/plugin-opener';
import { open } from '@tauri-apps/plugin-dialog';
import CustomSelect from '../components/CustomSelect.vue'; import CustomSelect from '../components/CustomSelect.vue';
const settings = useSettingsStore(); const settings = useSettingsStore();
const { showToast } = useToast(); const { showToast } = useToast();
const appVersion = ref(''); const appVersion = ref('');
const defaultDownloadPath = ref('');
onMounted(async () => { onMounted(async () => {
appVersion.value = await getVersion(); appVersion.value = await getVersion();
try {
defaultDownloadPath.value = await invoke<string>('get_default_download_path');
} catch {}
}); });
const closeActionValue = computed({ const closeActionValue = computed({
@ -132,33 +247,130 @@ const closeActionValue = computed({
set: (val: CloseAction) => settings.setCloseAction(val), set: (val: CloseAction) => settings.setCloseAction(val),
}); });
const downloadPathInput = ref(settings.downloadPath); async function pickDownloadFolder() {
const selected = await open({
directory: true,
multiple: false,
title: '选择下载路径',
});
if (selected) {
settings.setDownloadPath(selected);
showToast('下载路径已更新', 'success');
}
}
function clearDownloadPath() {
settings.setDownloadPath('');
showToast('已重置为默认路径', 'success');
}
const checkingUpdate = ref(false); const checkingUpdate = ref(false);
const updateMessage = ref(''); const updateMessage = ref('');
const updateMessageClass = ref('text-content-2'); const updateMessageClass = ref('text-content-2');
const latestRelease = ref<any>(null);
const showUpdateModal = ref(false);
const themeOptions = [ const themeOptions = [
{ label: '深色', value: 'dark' as const }, { label: '深色', value: 'dark' as const },
{ label: '浅色', value: 'light' as const }, { label: '浅色', value: 'light' as const },
]; ];
function saveDownloadPath() {
settings.setDownloadPath(downloadPathInput.value.trim());
showToast('下载路径已保存', 'success');
}
async function checkUpdate() { async function checkUpdate() {
checkingUpdate.value = true; checkingUpdate.value = true;
updateMessage.value = ''; updateMessage.value = '';
try { try {
await new Promise(r => setTimeout(r, 1500)); const resp = await fetch('https://gitea.atdunbg.xyz/api/v1/repos/atdunbg/Nekosonic-Music/releases?limit=1&draft=false');
updateMessage.value = '当前已是最新版本'; if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
updateMessageClass.value = 'text-accent-text'; const releases = await resp.json();
} catch { if (releases && releases.length > 0) {
updateMessage.value = '检查更新失败,请稍后重试'; latestRelease.value = releases[0];
showUpdateModal.value = true;
} else {
updateMessage.value = '暂无发布版本';
updateMessageClass.value = 'text-content-3';
}
} catch (e: any) {
updateMessage.value = `获取失败: ${e}`;
updateMessageClass.value = 'text-danger'; updateMessageClass.value = 'text-danger';
} finally { } finally {
checkingUpdate.value = false; checkingUpdate.value = false;
} }
} }
function formatDate(dateStr: string) {
try {
const d = new Date(dateStr);
return d.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' });
} catch {
return dateStr;
}
}
const recordingId = ref<string | null>(null);
function formatShortcut(key: string): string {
return key
.replace('Control', 'Ctrl')
.replace('ArrowLeft', '←')
.replace('ArrowRight', '→')
.replace('ArrowUp', '↑')
.replace('ArrowDown', '↓')
.replace(/\+/g, ' + ');
}
function startRecording(id: string) {
recordingId.value = id;
}
function resetShortcuts() {
settings.resetShortcuts();
showToast('快捷键已恢复默认', 'success');
}
const showResetConfirm = ref(false);
function handleResetAll() {
showResetConfirm.value = true;
}
function confirmResetAll() {
settings.resetAll();
showResetConfirm.value = false;
showToast('已恢复默认设置', 'success');
}
function onRecordingKeydown(e: KeyboardEvent) {
if (!recordingId.value) return;
e.preventDefault();
e.stopPropagation();
if (e.key === 'Escape') {
recordingId.value = null;
return;
}
const parts: string[] = [];
if (e.ctrlKey || e.metaKey) parts.push('Control');
if (e.altKey) parts.push('Alt');
if (e.shiftKey) parts.push('Shift');
const ignoredKeys = ['Control', 'Alt', 'Shift', 'Meta'];
if (!ignoredKeys.includes(e.key)) {
parts.push(e.code);
}
if (parts.length > 0 && !ignoredKeys.includes(e.key)) {
const combo = parts.join('+');
settings.setShortcut(recordingId.value, combo);
recordingId.value = null;
}
}
onMounted(() => {
window.addEventListener('keydown', onRecordingKeydown, true);
});
onBeforeUnmount(() => {
window.removeEventListener('keydown', onRecordingKeydown, true);
});
</script> </script>