Feat: 优化音频播放逻辑,添加设置页面
This commit is contained in:
104
main/main.js
104
main/main.js
@ -1,76 +1,117 @@
|
|||||||
const { app, BrowserWindow, ipcMain } = require("electron");
|
const { app, BrowserWindow, ipcMain, Menu } = require("electron");
|
||||||
const path = require("path");
|
const path = require("path");
|
||||||
const { spawn } = require('child_process')
|
const { spawn } = require("child_process");
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
|
|
||||||
app.disableHardwareAcceleration(); // 高 DPI 缩放修复
|
app.disableHardwareAcceleration(); // 高 DPI 缩放修复
|
||||||
|
|
||||||
// 音效播放器
|
// 音效播放器
|
||||||
function playAudioFile(filePath) {
|
function playAudioFile(filePath) {
|
||||||
if (process.platform === 'win32') {
|
if (process.platform === "win32") {
|
||||||
spawn('cmd', ['/c', `start "" "${filePath}"`])
|
spawn("cmd", ["/c", `start "" "${filePath}"`]);
|
||||||
} else if (process.platform === 'darwin') {
|
} else if (process.platform === "darwin") {
|
||||||
spawn('afplay', [filePath])
|
spawn("afplay", [filePath]);
|
||||||
} else {
|
} else {
|
||||||
spawn('aplay', [filePath])
|
spawn("aplay", [filePath]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ipcMain.on('play-sound', (_, soundFile) => {
|
ipcMain.on("play-sound", (_, soundFile) => {
|
||||||
let soundPath;
|
let soundPath;
|
||||||
|
|
||||||
// 判断是开发环境还是生产环境
|
// 判断是开发环境还是生产环境
|
||||||
if (process.env.NODE_ENV === 'development') {
|
if (process.env.NODE_ENV === "development") {
|
||||||
// 在开发模式下,直接指向 renderer/public 里的文件
|
// 在开发模式下,直接指向 renderer/public 里的文件
|
||||||
soundPath = path.join(__dirname, '../renderer/public/assets/sounds', soundFile);
|
soundPath = path.join(
|
||||||
|
__dirname,
|
||||||
|
"../renderer/public/assets/sounds",
|
||||||
|
soundFile
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
// 在生产模式下,Vite 会把 public 里的文件复制到 dist 文件夹
|
// 在生产模式下,Vite 会把 public 里的文件复制到 dist 文件夹
|
||||||
soundPath = path.join(__dirname, '../renderer/dist/assets/sounds', soundFile);
|
soundPath = path.join(
|
||||||
|
__dirname,
|
||||||
|
"../renderer/dist/assets/sounds",
|
||||||
|
soundFile
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('Main process trying to play sound at path:', soundPath);
|
console.log("Main process trying to play sound at path:", soundPath);
|
||||||
|
|
||||||
if (require('fs').existsSync(soundPath)) {
|
if (require("fs").existsSync(soundPath)) {
|
||||||
playAudioFile(soundPath);
|
playAudioFile(soundPath);
|
||||||
} else {
|
} else {
|
||||||
console.error('Sound file not found:', soundPath);
|
console.error("Sound file not found:", soundPath);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcMain.handle('get-sound-path', (_, soundFile) => {
|
ipcMain.handle("get-sound-path", (_, soundFile) => {
|
||||||
let soundPath;
|
let soundPath;
|
||||||
|
|
||||||
if (process.env.NODE_ENV === 'development') {
|
if (process.env.NODE_ENV === "development") {
|
||||||
soundPath = path.join(__dirname, '../renderer/public/assets/sounds', soundFile);
|
soundPath = path.join(
|
||||||
|
__dirname,
|
||||||
|
"../renderer/public/assets/sounds",
|
||||||
|
soundFile
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
soundPath = path.join(__dirname, '../renderer/dist/assets/sounds', soundFile);
|
soundPath = path.join(
|
||||||
|
__dirname,
|
||||||
|
"../renderer/dist/assets/sounds",
|
||||||
|
soundFile
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (require('fs').existsSync(soundPath)) {
|
if (require("fs").existsSync(soundPath)) {
|
||||||
// 返回一个可供 web 环境使用的 file 协议 URL
|
// 返回一个可供 web 环境使用的 file 协议 URL
|
||||||
return `file://${soundPath}`;
|
return `file://${soundPath}`;
|
||||||
} else {
|
} else {
|
||||||
console.error('Sound file not found:', soundPath);
|
console.error("Sound file not found:", soundPath);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcMain.handle('get-sound-files', async () => {
|
ipcMain.handle("get-sound-files", async () => {
|
||||||
const soundDir = process.env.NODE_ENV === 'development'
|
const soundDir =
|
||||||
? path.join(__dirname, '../renderer/public/assets/sounds')
|
process.env.NODE_ENV === "development"
|
||||||
: path.join(__dirname, '../renderer/dist/assets/sounds');
|
? path.join(__dirname, "../renderer/public/assets/sounds")
|
||||||
|
: path.join(__dirname, "../renderer/dist/assets/sounds");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 读取目录下的所有文件名
|
// 读取目录下的所有文件名
|
||||||
const files = await fs.promises.readdir(soundDir);
|
const files = await fs.promises.readdir(soundDir);
|
||||||
// 筛选出 .mp3 文件并返回
|
// 筛选出 .mp3 文件并返回
|
||||||
return files.filter(file => file.endsWith('.mp3'));
|
return files.filter((file) => file.endsWith(".mp3"));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('无法读取声音目录:', error);
|
console.error("无法读取声音目录:", error);
|
||||||
return []; // 如果出错则返回空数组
|
return []; // 如果出错则返回空数组
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
ipcMain.on("show-context-menu", () => {
|
||||||
|
const template = [
|
||||||
|
{
|
||||||
|
label: "置顶显示",
|
||||||
|
type: "checkbox",
|
||||||
|
checked: isAlwaysOnTop, // 菜单项的选中状态与变量同步
|
||||||
|
click: () => {
|
||||||
|
isAlwaysOnTop = !isAlwaysOnTop; // 点击时切换状态
|
||||||
|
mainWindow.setAlwaysOnTop(isAlwaysOnTop); // 并应用到窗口
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ type: "separator" }, // 分隔线
|
||||||
|
{
|
||||||
|
label: "退出",
|
||||||
|
click: () => {
|
||||||
|
app.quit(); // 点击时退出应用
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const menu = Menu.buildFromTemplate(template);
|
||||||
|
menu.popup({ window: mainWindow }); // 在主窗口上弹出菜单
|
||||||
|
});
|
||||||
|
|
||||||
|
let isAlwaysOnTop = true;
|
||||||
let mainWindow;
|
let mainWindow;
|
||||||
|
|
||||||
function createWindow() {
|
function createWindow() {
|
||||||
@ -78,10 +119,11 @@ function createWindow() {
|
|||||||
width: 200,
|
width: 200,
|
||||||
height: 200,
|
height: 200,
|
||||||
transparent: true, // 开启透明窗口
|
transparent: true, // 开启透明窗口
|
||||||
frame: false, // 无边框窗口
|
frame: false, // 无边框窗口
|
||||||
resizable: false, // 禁止调整大小
|
resizable: false, // 禁止调整大小
|
||||||
title: "说的道理桌宠",
|
title: "说的道理桌宠",
|
||||||
icon: path.join(__dirname, '../build/icon.png'),
|
alwaysOnTop: isAlwaysOnTop, // 窗口始终在最上层
|
||||||
|
icon: path.join(__dirname, "../build/icon.png"),
|
||||||
webPreferences: {
|
webPreferences: {
|
||||||
preload: path.join(__dirname, "preload.js"),
|
preload: path.join(__dirname, "preload.js"),
|
||||||
contextIsolation: true,
|
contextIsolation: true,
|
||||||
@ -90,13 +132,13 @@ function createWindow() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// 当渲染进程传来这个事件时,就移动窗口
|
// 当渲染进程传来这个事件时,就移动窗口
|
||||||
ipcMain.on('move-window', (event, { x, y }) => {
|
ipcMain.on("move-window", (event, { x, y }) => {
|
||||||
// 使用 Math.round 避免非整数坐标可能带来的问题
|
// 使用 Math.round 避免非整数坐标可能带来的问题
|
||||||
mainWindow.setPosition(Math.round(x), Math.round(y), false);
|
mainWindow.setPosition(Math.round(x), Math.round(y), false);
|
||||||
});
|
});
|
||||||
|
|
||||||
// 添加一个 handle,用于响应前端获取窗口位置的请求
|
// 添加一个 handle,用于响应前端获取窗口位置的请求
|
||||||
ipcMain.handle('get-window-position', () => {
|
ipcMain.handle("get-window-position", () => {
|
||||||
if (mainWindow) {
|
if (mainWindow) {
|
||||||
const [x, y] = mainWindow.getPosition();
|
const [x, y] = mainWindow.getPosition();
|
||||||
return { x, y };
|
return { x, y };
|
||||||
|
@ -16,5 +16,6 @@ contextBridge.exposeInMainWorld('electronAPI', {
|
|||||||
},
|
},
|
||||||
moveWindow: (position) => ipcRenderer.send('move-window', position),
|
moveWindow: (position) => ipcRenderer.send('move-window', position),
|
||||||
// 暴露获取窗口位置的函数
|
// 暴露获取窗口位置的函数
|
||||||
getWindowPosition: () => ipcRenderer.invoke('get-window-position')
|
getWindowPosition: () => ipcRenderer.invoke('get-window-position'),
|
||||||
|
showContextMenu: () => ipcRenderer.send('show-context-menu')
|
||||||
})
|
})
|
@ -2,9 +2,9 @@
|
|||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
<link rel="icon" type="image/svg+xml" href="assets/icon.png" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>Vite + Vue + TS</title>
|
<title>说的道理桌宠</title>
|
||||||
</head>
|
</head>
|
||||||
<body style="background-color: transparent;">
|
<body style="background-color: transparent;">
|
||||||
<div id="app"></div>
|
<div id="app"></div>
|
||||||
|
BIN
renderer/public/assets/images/icon.png
Normal file
BIN
renderer/public/assets/images/icon.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 90 KiB |
@ -8,6 +8,7 @@ const soundFiles = ref([]); // 存储从主进程获取的声音文件名列
|
|||||||
const showTooltip = ref(false);
|
const showTooltip = ref(false);
|
||||||
const currentTooltip = ref("");
|
const currentTooltip = ref("");
|
||||||
const isLoading = ref(true); // 跟踪文件列表是否已加载
|
const isLoading = ref(true); // 跟踪文件列表是否已加载
|
||||||
|
const isPlaying = ref(false); // 是否正在播放音效,用作锁
|
||||||
|
|
||||||
// 在组件挂载后,从主进程获取声音文件列表
|
// 在组件挂载后,从主进程获取声音文件列表
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
@ -23,17 +24,39 @@ onMounted(async () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const playRandomSound = async () => {
|
const playRandomSound = async () => {
|
||||||
|
if (isPlaying.value) return;
|
||||||
if (isLoading.value || soundFiles.value.length === 0) return;
|
if (isLoading.value || soundFiles.value.length === 0) return;
|
||||||
const randomSoundFile = soundFiles.value[Math.floor(Math.random() * soundFiles.value.length)];
|
const randomSoundFile = soundFiles.value[Math.floor(Math.random() * soundFiles.value.length)];
|
||||||
|
isPlaying.value = true; // 加锁
|
||||||
try {
|
try {
|
||||||
const audioUrl = await window.electronAPI.getSoundPath(randomSoundFile);
|
const audioUrl = await window.electronAPI.getSoundPath(randomSoundFile);
|
||||||
if (audioUrl) new Howl({ src: [audioUrl], format: ["mp3"] }).play();
|
if (audioUrl) {
|
||||||
|
new Howl({
|
||||||
|
src: [audioUrl],
|
||||||
|
format: ["mp3"],
|
||||||
|
// 当音频播放结束时
|
||||||
|
onend: function() {
|
||||||
|
// 隐藏提示框
|
||||||
|
showTooltip.value = false;
|
||||||
|
// 解锁,允许下一次点击
|
||||||
|
isPlaying.value = false;
|
||||||
|
}
|
||||||
|
}).play();
|
||||||
|
} else {
|
||||||
|
// 如果音频路径获取失败,也要解锁
|
||||||
|
isPlaying.value = false;
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
// 如果播放过程出错,也要解锁
|
||||||
|
isPlaying.value = false;
|
||||||
console.error("播放失败:", err);
|
console.error("播放失败:", err);
|
||||||
}
|
}
|
||||||
currentTooltip.value = randomSoundFile.replace(/\.mp3$/, '');
|
if (randomSoundFile === "哇袄.mp3") {
|
||||||
|
currentTooltip.value = "哇袄!!!";
|
||||||
|
} else {
|
||||||
|
currentTooltip.value = randomSoundFile.replace(/\.mp3$/, '');
|
||||||
|
}
|
||||||
showTooltip.value = true;
|
showTooltip.value = true;
|
||||||
setTimeout(() => (showTooltip.value = false), 2000);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const dragState = reactive({
|
const dragState = reactive({
|
||||||
@ -48,6 +71,10 @@ const dragState = reactive({
|
|||||||
|
|
||||||
// 鼠标按下事件 (改为异步函数)
|
// 鼠标按下事件 (改为异步函数)
|
||||||
async function handleMouseDown(event) {
|
async function handleMouseDown(event) {
|
||||||
|
// 如果按下的不是鼠标左键,则不执行任何操作
|
||||||
|
if (event.button !== 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
// 在拖动开始时,先获取窗口的当前位置
|
// 在拖动开始时,先获取窗口的当前位置
|
||||||
const { x, y } = await window.electronAPI.getWindowPosition();
|
const { x, y } = await window.electronAPI.getWindowPosition();
|
||||||
dragState.windowStartX = x;
|
dragState.windowStartX = x;
|
||||||
@ -98,10 +125,18 @@ function handleMouseUp() {
|
|||||||
window.removeEventListener('mousemove', handleMouseMove);
|
window.removeEventListener('mousemove', handleMouseMove);
|
||||||
window.removeEventListener('mouseup', handleMouseUp);
|
window.removeEventListener('mouseup', handleMouseUp);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function handleRightClick() {
|
||||||
|
window.electronAPI.showContextMenu();
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="pet-container" @mousedown="handleMouseDown">
|
<div
|
||||||
|
class="pet-container"
|
||||||
|
@mousedown="handleMouseDown"
|
||||||
|
@contextmenu.prevent="handleRightClick"
|
||||||
|
>
|
||||||
<transition name="fade">
|
<transition name="fade">
|
||||||
<div v-if="showTooltip" class="tooltip">
|
<div v-if="showTooltip" class="tooltip">
|
||||||
{{ currentTooltip }}
|
{{ currentTooltip }}
|
||||||
|
Reference in New Issue
Block a user