Update: 使用 howler 优化音效播放逻辑

This commit is contained in:
2025-08-08 20:06:52 +08:00
parent 86a59aff1f
commit 1f954aad35
3 changed files with 36 additions and 4 deletions

View File

@ -34,6 +34,24 @@ ipcMain.on('play-sound', (_, soundFile) => {
} }
}); });
ipcMain.handle('get-sound-path', (_, soundFile) => {
let soundPath;
if (process.env.NODE_ENV === 'development') {
soundPath = path.join(__dirname, '../renderer/public/assets/sounds', soundFile);
} else {
soundPath = path.join(__dirname, '../renderer/dist/assets/sounds', soundFile);
}
if (require('fs').existsSync(soundPath)) {
// 返回一个可供 web 环境使用的 file 协议 URL
return `file://${soundPath}`;
} else {
console.error('Sound file not found:', soundPath);
return null;
}
});
let mainWindow; let mainWindow;
function createWindow() { function createWindow() {
@ -46,6 +64,7 @@ function createWindow() {
webPreferences: { webPreferences: {
preload: path.join(__dirname, "preload.js"), preload: path.join(__dirname, "preload.js"),
contextIsolation: true, contextIsolation: true,
webSecurity: false, // 信任应用,并允许加载本地资源
}, },
}); });

View File

@ -8,6 +8,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
console.error('播放音效失败:', err) console.error('播放音效失败:', err)
} }
}, },
getSoundPath: (soundFile) => ipcRenderer.invoke('get-sound-path', soundFile),
showTooltip: (text) => ipcRenderer.send('show-tooltip', text), showTooltip: (text) => ipcRenderer.send('show-tooltip', text),
onUpdatePosition: (callback) => { onUpdatePosition: (callback) => {
ipcRenderer.on('update-position', (_, position) => callback(position)) ipcRenderer.on('update-position', (_, position) => callback(position))

View File

@ -1,6 +1,7 @@
<script setup> <script setup>
import { ref, onMounted } from "vue"; import { ref, onMounted } from "vue";
import petGif from "./assets/pet.gif"; import petGif from "./assets/pet.gif";
import { Howl } from 'howler';
// 配置数据 // 配置数据
const tooltips = [ const tooltips = [
@ -27,13 +28,24 @@ const position = ref({ x: 0, y: 0 });
// 点击事件处理 // 点击事件处理
const handleClick = async () => { const handleClick = async () => {
const randomSound = soundFiles[Math.floor(Math.random() * soundFiles.length)]; const randomSoundFile = soundFiles[Math.floor(Math.random() * soundFiles.length)];
console.log('尝试播放:', randomSound) console.log('请求播放:', randomSoundFile);
try { try {
window.electronAPI?.playSound(randomSound) const audioUrl = await window.electronAPI?.getSoundPath(randomSoundFile);
if (audioUrl) {
const sound = new Howl({
src: [audioUrl],
format: ['mp3']
});
sound.play();
} else {
console.error('无法获取音频路径:', randomSoundFile);
}
} catch (err) { } catch (err) {
console.error('播放失败:', err) console.error('播放失败:', err);
} }
currentTooltip.value = tooltips[Math.floor(Math.random() * tooltips.length)]; currentTooltip.value = tooltips[Math.floor(Math.random() * tooltips.length)];