feat: 修改路由 和 播放背景

This commit is contained in:
alger
2023-12-16 13:42:52 +08:00
parent 086bbb8958
commit 1360d7c481
5 changed files with 233 additions and 158 deletions
+2 -1
View File
@@ -4,4 +4,5 @@ dist
dist-ssr dist-ssr
*.local *.local
pnpm-lock.yaml pnpm-lock.yaml
dist.zip
BIN
View File
Binary file not shown.
+221 -147
View File
@@ -2,27 +2,32 @@
<!-- 展开全屏 --> <!-- 展开全屏 -->
<transition name="musicPage"> <transition name="musicPage">
<div id="drawer-target" v-show="musicFull"> <div id="drawer-target" v-show="musicFull">
<div class="drawer-target-back" :style="{backgroundImage:`url(${getImgUrl( playMusic?.picUrl, '300y300')})`}"></div> <!-- <div class="drawer-target-back" :style="{backgroundImage:`url(${getImgUrl( playMusic?.picUrl, '300y300')})`}"></div> -->
<div class="music-img"> <div class="music-img">
<n-image <n-image :src="getImgUrl( playMusic?.picUrl, '300y300')" class="img" lazy preview-disabled />
:src="getImgUrl( playMusic?.picUrl, '300y300')"
class="img"
lazy
preview-disabled
/>
</div> </div>
<div class="music-content"> <div class="music-content">
<div class="music-content-name">{{ playMusic.song.name }}</div> <div class="music-content-name">{{ playMusic.song.name }}</div>
<div class="music-content-singer"> <div class="music-content-singer">
<span v-for="(item, index) in playMusic.song.artists" :key="index">{{ item.name <span v-for="(item, index) in playMusic.song.artists" :key="index">
}}{{ index < playMusic.song.artists.length - 1 ? ' / ' : '' }}</span> {{ item.name
}}{{ index < playMusic.song.artists.length - 1 ? ' / ' : '' }}
</span>
</div> </div>
<n-layout class="music-lrc" style="height: 550px" ref="lrcSider" :native-scrollbar="false" <n-layout
@mouseover="mouseOverLayout" @mouseleave="mouseLeaveLayout"> class="music-lrc"
style="height: 550px"
ref="lrcSider"
:native-scrollbar="false"
@mouseover="mouseOverLayout"
@mouseleave="mouseLeaveLayout"
>
<template v-for="(item, index) in lrcArray" :key="index"> <template v-for="(item, index) in lrcArray" :key="index">
<div class="music-lrc-text" :class="{ 'now-text': isCurrentLrc(index) }" @click="setAudioTime(index)"> <div
{{ item.text }} class="music-lrc-text"
</div> :class="{ 'now-text': isCurrentLrc(index) }"
@click="setAudioTime(index)"
>{{ item.text }}</div>
</template> </template>
</n-layout> </n-layout>
</div> </div>
@@ -31,22 +36,26 @@
<!-- 底部播放栏 --> <!-- 底部播放栏 -->
<div class="music-play-bar" :class="setAnimationClass('animate__bounceInUp')"> <div class="music-play-bar" :class="setAnimationClass('animate__bounceInUp')">
<n-image <n-image
:src="getImgUrl( playMusic?.picUrl, '300y300')" :src="getImgUrl( playMusic?.picUrl, '300y300')"
class="play-bar-img" class="play-bar-img"
lazy lazy
preview-disabled preview-disabled
@click="setMusicFull" @click="setMusicFull"
/> />
<div class="music-content"> <div class="music-content">
<div class="music-content-title"> <div class="music-content-title">
<n-ellipsis class="text-ellipsis" line-clamp="1">{{ <n-ellipsis class="text-ellipsis" line-clamp="1">
{{
playMusic.name playMusic.name
}}</n-ellipsis> }}
</n-ellipsis>
</div> </div>
<div class="music-content-name"> <div class="music-content-name">
<n-ellipsis class="text-ellipsis" line-clamp="1"> <n-ellipsis class="text-ellipsis" line-clamp="1">
<span v-for="(item, index) in playMusic.song.artists" :key="index">{{ item.name <span v-for="(item, index) in playMusic.song.artists" :key="index">
}}{{ index < playMusic.song.artists.length - 1 ? ' / ' : '' }}</span> {{ item.name
}}{{ index < playMusic.song.artists.length - 1 ? ' / ' : '' }}
</span>
</n-ellipsis> </n-ellipsis>
</div> </div>
</div> </div>
@@ -98,40 +107,40 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import type { SongResult } from '@/type/music' import type { SongResult } from "@/type/music";
import type { ILyric } from '@/type/lyric' import type { ILyric } from "@/type/lyric";
import { secondToMinute, getImgUrl} from '@/utils' import { secondToMinute, getImgUrl } from "@/utils";
import { computed, onMounted, ref, watch } from 'vue' import { computed, nextTick, onMounted, ref, watch } from "vue";
import { useStore } from 'vuex' import { useStore } from "vuex";
import { setAnimationClass } from '@/utils' import { setAnimationClass } from "@/utils";
import { getMusicLrc, getParsingMusicUrl } from '@/api/music' import { getMusicLrc, getParsingMusicUrl } from "@/api/music";
import axios from 'axios' import axios from "axios";
const store = useStore() const store = useStore();
const audio = ref<any>(null) const audio = ref<any>(null);
// 播放的音乐信息 // 播放的音乐信息
const playMusic = computed(() => store.state.playMusic as SongResult) const playMusic = computed(() => store.state.playMusic as SongResult);
// 是否播放 // 是否播放
const play = computed(() => store.state.play as boolean) const play = computed(() => store.state.play as boolean);
// 播放链接 // 播放链接
const ProxyUrl = const ProxyUrl =
import.meta.env.VITE_API_PROXY + '' || 'http://110.42.251.190:9856' import.meta.env.VITE_API_PROXY + "" || "http://110.42.251.190:9856";
const playMusicUrl = ref('') const playMusicUrl = ref("");
watch( watch(
() => store.state.playMusicUrl, () => store.state.playMusicUrl,
async (value, oldValue) => { async (value, oldValue) => {
const isUrlHasMc = location.href.includes('mc.') const isUrlHasMc = location.href.includes("mc.");
if (value && isUrlHasMc) { if (value && isUrlHasMc) {
let playMusicUrl1 = value as string let playMusicUrl1 = value as string;
if (!ProxyUrl) { if (!ProxyUrl) {
playMusicUrl.value = playMusicUrl1 playMusicUrl.value = playMusicUrl1;
return return;
} }
const url = new URL(playMusicUrl1) const url = new URL(playMusicUrl1);
const pathname = url.pathname const pathname = url.pathname;
const subdomain = url.origin.split('.')[0].split('//')[1] const subdomain = url.origin.split(".")[0].split("//")[1];
playMusicUrl1 = `${ProxyUrl}/mc?m=${subdomain}&url=${pathname}` playMusicUrl1 = `${ProxyUrl}/mc?m=${subdomain}&url=${pathname}`;
// console.log('playMusicUrl1', playMusicUrl1) // console.log('playMusicUrl1', playMusicUrl1)
// // 获取音频文件 // // 获取音频文件
// const { data } = await axios.get(playMusicUrl1, { // const { data } = await axios.get(playMusicUrl1, {
@@ -140,18 +149,18 @@ watch(
// const musicUrl = URL.createObjectURL(data) // const musicUrl = URL.createObjectURL(data)
// console.log('musicUrl', musicUrl) // console.log('musicUrl', musicUrl)
// playMusicUrl.value = musicUrl // playMusicUrl.value = musicUrl
playMusicUrl.value = playMusicUrl1 playMusicUrl.value = playMusicUrl1;
console.log('playMusicUrl1',playMusicUrl1) console.log("playMusicUrl1", playMusicUrl1);
setTimeout(() => { setTimeout(() => {
onAudio(audio.value) onAudio(audio.value);
store.commit('setPlayMusic', true) store.commit("setPlayMusic", true);
}, 100) }, 100);
}else { } else {
playMusicUrl.value = value playMusicUrl.value = value;
} }
}, },
{ immediate: true } { immediate: true }
) );
// 获取音乐播放Dom // 获取音乐播放Dom
onMounted(() => { onMounted(() => {
@@ -160,105 +169,166 @@ onMounted(() => {
() => play.value, () => play.value,
(value, oldValue) => { (value, oldValue) => {
if (value) { if (value) {
audio.value.play() audio.value.play();
onAudio(audio.value) onAudio(audio.value);
} else { } else {
audio.value.pause() audio.value.pause();
} }
} }
) );
watch( watch(
() => playMusicUrl.value, () => playMusicUrl.value,
(value, oldValue) => { (value, oldValue) => {
if (!value) { if (!value) {
parsingMusic() parsingMusic();
} }
} }
) );
// 抬起键盘按钮监听 // 抬起键盘按钮监听
document.onkeyup = (e) => { document.onkeyup = (e) => {
switch (e.code) { switch (e.code) {
case 'Space': case "Space":
playMusicEvent() playMusicEvent();
} }
} };
// 按下键盘按钮监听 // 按下键盘按钮监听
document.onkeydown = (e) => { document.onkeydown = (e) => {
switch (e.code) { switch (e.code) {
case 'Space': case "Space":
return false return false;
}
};
nextTick(() => {
const img = document.querySelector(".play-bar-img img") as HTMLImageElement;
img.onload = () => {
// const colorList = new Array(3).fill('').map(() => getImgColor(img.src) + randomPercent()).sort(() => Math.random() - 0.5)
// const colorStr = colorList.join(',')
// const playBar = document.querySelector('.music-play-bar') as HTMLElement
// playBar.style.background = `linear-gradient(90deg, ${colorStr})`
// 随机角度
const angle = Math.floor(Math.random() * 360) + "deg";
const drawerTarget = document.querySelector(
"#drawer-target"
) as HTMLElement;
drawerTarget.style.background = `linear-gradient(${angle}, ${getImgColor(
img.src
)})`;
// 背景色散开 不要线性 也不是圆形、
// drawerTarget.style.background = `radial-gradient(circle, ${colorStr})`
/*
background-image: linear-gradient( 58.2deg, rgba(40,91,212,0.73) -3%, rgba(171,53,163,0.45) 49.3%, rgba(255,204,112,0.37) 97.7% );
*/
};
});
});
const randomPercent = () => {
const percent = Math.floor(Math.random() * 201) - 100;
return ` ${percent}%`;
};
// 获取图片的主要颜色生成css渐变色
const getImgColor = (url: string) => {
const img = document.querySelector(".play-bar-img img") as HTMLImageElement;
// 设置跨域
img.crossOrigin = "Anonymous";
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
ctx?.drawImage(img, 0, 0, img.width, img.height);
const data = ctx?.getImageData(0, 0, img.width, img.height).data;
const colorArr = [];
for (let i = 0; i < data!.length; i += 4) {
const r = data![i];
const g = data![i + 1];
const b = data![i + 2];
const a = data![i + 3];
if (a > 0 && r < 200 && g < 200 && b < 200) {
colorArr.push([r, g, b]);
} }
} }
})
const nowTime = ref(0) const color = colorArr[Math.floor(Math.random() * colorArr.length)];
const allTime = ref(0) const colorStr = `rgb(${color[0]},${color[1]},${color[2]})`;
const colorList = new Array(3)
.fill("")
.map(() => colorArr[Math.floor(Math.random() * colorArr.length)])
.sort((item) => item.reduce((a, b) => a + b))
.map((item) => `rgb(${item[0]},${item[1]},${item[2]})` + randomPercent())
.join(",");
return colorList;
};
const nowTime = ref(0);
const allTime = ref(0);
// 计算属性 获取当前播放时间的进度 // 计算属性 获取当前播放时间的进度
const timeSlider = computed({ const timeSlider = computed({
get: () => (nowTime.value / allTime.value) * 100, get: () => (nowTime.value / allTime.value) * 100,
set: (value) => { set: (value) => {
audio.value.currentTime = (value * allTime.value) / 100 audio.value.currentTime = (value * allTime.value) / 100;
audio.value.play() audio.value.play();
store.commit('setPlayMusic', true) store.commit("setPlayMusic", true);
}, },
}) });
// 音量条 // 音量条
const audioVolume = ref(1) const audioVolume = ref(1);
const volumeSlider = computed({ const volumeSlider = computed({
get: () => audioVolume.value * 100, get: () => audioVolume.value * 100,
set: (value) => { set: (value) => {
audio.value.volume = value / 100 audio.value.volume = value / 100;
}, },
}) });
// 获取当前播放时间 // 获取当前播放时间
const getNowTime = computed(() => { const getNowTime = computed(() => {
return secondToMinute(nowTime.value) return secondToMinute(nowTime.value);
}) });
// 获取总时间 // 获取总时间
const getAllTime = computed(() => { const getAllTime = computed(() => {
return secondToMinute(allTime.value) return secondToMinute(allTime.value);
}) });
// 获取歌词滚动dom // 获取歌词滚动dom
const lrcSider = ref<any>(null) const lrcSider = ref<any>(null);
// 当前播放的是哪一句歌词 // 当前播放的是哪一句歌词
const newLrcIndex = ref(0) const newLrcIndex = ref(0);
const isMouse = ref(false) const isMouse = ref(false);
// 歌词滚动方法 // 歌词滚动方法
const lrcScroll = () => { const lrcScroll = () => {
if (musicFull.value && !isMouse.value) { if (musicFull.value && !isMouse.value) {
let top = newLrcIndex.value * 50 - 225 let top = newLrcIndex.value * 50 - 225;
lrcSider.value.scrollTo({ top: top, behavior: 'smooth' }) lrcSider.value.scrollTo({ top: top, behavior: "smooth" });
} }
} };
const mouseOverLayout = () => { const mouseOverLayout = () => {
isMouse.value = true isMouse.value = true;
} };
const mouseLeaveLayout = () => { const mouseLeaveLayout = () => {
setTimeout(() => { setTimeout(() => {
isMouse.value = false isMouse.value = false;
}, 3000) }, 3000);
} };
// 监听音乐播放 获取时间 // 监听音乐播放 获取时间
const onAudio = (audio: HTMLAudioElement) => { const onAudio = (audio: HTMLAudioElement) => {
audio.removeEventListener('timeupdate', handleGetAudioTime); audio.removeEventListener("timeupdate", handleGetAudioTime);
audio.removeEventListener('ended', handleEnded); audio.removeEventListener("ended", handleEnded);
audio.addEventListener('timeupdate', handleGetAudioTime); audio.addEventListener("timeupdate", handleGetAudioTime);
audio.addEventListener('ended', handleEnded); audio.addEventListener("ended", handleEnded);
} };
function handleEnded() { function handleEnded() {
store.commit('nextPlay'); store.commit("nextPlay");
} }
function handlePrev(){ function handlePrev() {
store.commit('prevPlay'); store.commit("prevPlay");
} }
function handleGetAudioTime(this: any) { function handleGetAudioTime(this: any) {
@@ -276,119 +346,122 @@ function handleGetAudioTime(this: any) {
// 播放暂停按钮事件 // 播放暂停按钮事件
const playMusicEvent = async () => { const playMusicEvent = async () => {
if (play.value) { if (play.value) {
store.commit('setPlayMusic', false) store.commit("setPlayMusic", false);
} else { } else {
store.commit('setPlayMusic', true) store.commit("setPlayMusic", true);
} }
} };
const musicFull = ref(false) const musicFull = ref(false);
// 设置musicFull // 设置musicFull
const setMusicFull = () => { const setMusicFull = () => {
musicFull.value = !musicFull.value musicFull.value = !musicFull.value;
if (musicFull.value) { if (musicFull.value) {
loadLrc() loadLrc();
} }
} };
// 解析音乐 // 解析音乐
const parsingMusic = async () => { const parsingMusic = async () => {
const { data } = await getParsingMusicUrl(playMusic.value.id) const { data } = await getParsingMusicUrl(playMusic.value.id);
store.state.playMusicUrl = data.data.url store.state.playMusicUrl = data.data.url;
} };
const lrcData = ref<ILyric>() const lrcData = ref<ILyric>();
interface ILrcData { interface ILrcData {
text: string text: string;
trText: string trText: string;
} }
const lrcArray = ref<Array<ILrcData>>() const lrcArray = ref<Array<ILrcData>>();
const lrcTimeArray = ref<Array<Number>>([]) const lrcTimeArray = ref<Array<Number>>([]);
// 加载歌词 // 加载歌词
const loadLrc = async () => { const loadLrc = async () => {
const { data } = await getMusicLrc(playMusic.value.id) const { data } = await getMusicLrc(playMusic.value.id);
lrcData.value = data lrcData.value = data;
try { try {
let musicText = data.lrc.lyric let musicText = data.lrc.lyric;
//歌词时间 //歌词时间
let timeArray = musicText.match(/(\d{2}):(\d{2})(\.(\d*))?/g) let timeArray = musicText.match(/(\d{2}):(\d{2})(\.(\d*))?/g);
let timeArrayNum: Array<Number> = [] let timeArrayNum: Array<Number> = [];
timeArray?.forEach(function (item, index) { timeArray?.forEach(function (item, index) {
if (item.length < 9) { if (item.length < 9) {
item = item + '0' item = item + "0";
} }
timeArrayNum.push( timeArrayNum.push(
parseInt(item.split(':')[0]) * 60 + parseFloat(item.split(':')[1]) parseInt(item.split(":")[0]) * 60 + parseFloat(item.split(":")[1])
) );
}) });
lrcTimeArray.value = timeArrayNum lrcTimeArray.value = timeArrayNum;
//歌词 //歌词
let musicTextArray = musicText let musicTextArray = musicText
.replace(/(\[(\d{2}):(\d{2})(\.(\d*))?\])/g, '') .replace(/(\[(\d{2}):(\d{2})(\.(\d*))?\])/g, "")
.split('\n') .split("\n");
let text = [] let text = [];
try { try {
let trMusicText = data.tlyric.lyric let trMusicText = data.tlyric.lyric;
let trMusicTextArray = trMusicText let trMusicTextArray = trMusicText
.replace(/(\[(\d{2}):(\d{2})(\.(\d*))?\])/g, '') .replace(/(\[(\d{2}):(\d{2})(\.(\d*))?\])/g, "")
.split('\n') .split("\n");
for (let i = 0; i < musicTextArray.length - 1; i++) { for (let i = 0; i < musicTextArray.length - 1; i++) {
text.push({ text.push({
text: musicTextArray[i], text: musicTextArray[i],
trText: trMusicTextArray[i], trText: trMusicTextArray[i],
}) });
} }
lrcArray.value = text lrcArray.value = text;
} catch (err) { } catch (err) {
text = [] text = [];
} }
} catch (err) { } catch (err) {
console.log(err) console.log(err);
} }
} };
// 是否是当前正在播放的歌词 // 是否是当前正在播放的歌词
const isCurrentLrc = (index: any) => { const isCurrentLrc = (index: any) => {
let isTrue = !(nowTime.value <= lrcTimeArray.value[index] || nowTime.value >= lrcTimeArray.value[index + 1]) let isTrue = !(
nowTime.value <= lrcTimeArray.value[index] ||
nowTime.value >= lrcTimeArray.value[index + 1]
);
if (isTrue) { if (isTrue) {
newLrcIndex.value = index newLrcIndex.value = index;
} }
return isTrue return isTrue;
} };
// 设置当前播放时间 // 设置当前播放时间
const setAudioTime = (index: any) => { const setAudioTime = (index: any) => {
audio.value.currentTime = lrcTimeArray.value[index] audio.value.currentTime = lrcTimeArray.value[index];
audio.value.play() audio.value.play();
} };
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.musicPage-enter-active { .musicPage-enter-active {
animation: fadeInUp 0.8s ease-in-out; animation: fadeInUp 0.4s ease-in-out;
} }
.musicPage-leave-active { .musicPage-leave-active {
animation: fadeOutDown 0.8s ease-in-out; animation: fadeOutDown 0.4s ease-in-out;
} }
.drawer-target-back{ .drawer-target-back {
position: absolute; position: absolute;
width: 100%; width: 100%;
height: 100%; height: 100%;
z-index: -1; z-index: -1;
left: 0; left: 0;
opacity: 0.8; opacity: 0.8;
filter: blur(143px) brightness(80%); // filter: blur(143px) brightness(80%);
background-size: 100%; background-size: 100%;
} }
#drawer-target { #drawer-target {
@apply top-0 left-0 absolute w-full h-full overflow-hidden rounded px-24 pt-24 pb-48 flex items-center; @apply top-0 left-0 absolute w-full h-full overflow-hidden rounded px-24 pt-24 pb-48 flex items-center;
backdrop-filter: saturate(180%) blur(50px); // backdrop-filter: saturate(180%) blur(50px);
// background-color: #333333; // background-color: #333333;
animation-duration: 300ms; animation-duration: 300ms;
@@ -398,6 +471,7 @@ const setAudioTime = (index: any) => {
.img { .img {
width: 450px; width: 450px;
height: 450px;
@apply rounded-xl; @apply rounded-xl;
} }
} }
@@ -475,7 +549,7 @@ const setAudioTime = (index: any) => {
@apply flex items-center; @apply flex items-center;
>div { > div {
@apply cursor-pointer; @apply cursor-pointer;
} }
+10 -10
View File
@@ -1,21 +1,21 @@
import { createRouter, createWebHistory, createMemoryHistory } from "vue-router" import { createRouter, createWebHashHistory } from 'vue-router'
import AppLayout from "@/layout/AppLayout.vue" import AppLayout from '@/layout/AppLayout.vue'
import homeRouter from "@/router/home" import homeRouter from '@/router/home'
let loginRouter = { let loginRouter = {
path: "/login", path: '/login',
name: "login", name: 'login',
mate: { mate: {
keepAlive: true, keepAlive: true,
title: "登录", title: '登录',
icon: "icon-Home", icon: 'icon-Home',
}, },
component: () => import("@/views/login/index.vue"), component: () => import('@/views/login/index.vue'),
} }
const routes = [ const routes = [
{ {
path: "/", path: '/',
component: AppLayout, component: AppLayout,
children: [...homeRouter, loginRouter], children: [...homeRouter, loginRouter],
}, },
@@ -23,5 +23,5 @@ const routes = [
export default createRouter({ export default createRouter({
routes: routes, routes: routes,
history: createWebHistory(), history: createWebHashHistory(),
}) })
View File