我在这里和GitHub上的每一个帖子上都try 了每一种方法. 我try 使用了一个HTML音频标记,使用ipcReneller/ipcMain API创建了一个播放音频的新窗口,并try 了每个库来播放声音,但仍然一无所获.有没有人知道如何在里面播放音频文件?
我在这里和GitHub上的每一个帖子上都try 了每一种方法. 我try 使用了一个HTML音频标记,使用ipcReneller/ipcMain API创建了一个播放音频的新窗口,并try 了每个库来播放声音,但仍然一无所获.有没有人知道如何在里面播放音频文件?
因此,经过几天的彻底测试和try ,我找到了使用ElectronJS中的协议API播放音频文件的方法:
在主要流程中:
import { protocol } from "electron"
// ... some other code here
const registerAssetProtocol = async (): Promise<void> => {
return new Promise<void>((resolve) => {
protocol.registerFileProtocol('asset', (request, callback) => {
const assetName = request.url.substr(8); // Remove 'asset://'
const assetPath = path.normalize(
path.join(__dirname, '../assets/', assetName)
);
console.log('Asset Path:', assetPath);
callback({
path: assetPath,
headers: {
'content-type': 'audio/mpeg',
},
});
});
// Due to the way registerFileProtocol works, it doesn't provide a direct error callback.
// If there's an error, you would have to handle it inside the callback itself.
// Here, we're simply resolving after the registration attempt.
resolve();
});
};
然后在您想要播放音频文件的组件中,在我的例子中是一个Reaction组件,音频文件在点击一个元素时触发:
// This is the function that triggers the audio play
// ... some other code here
function toggleCompletionState() {
if (!isComplete) {
// Assuming you want to play the audio when task is completed
const todoCompletionChime = new Audio(
'asset://audio/chimes/todoCompletionChime.mp3'
);
todoCompletionChime.play();
}
setIsComplete(!isComplete);
}
//... other code here
<button
type="button"
className={`rounded-full h-7 w-7 flex flex-row items-center justify-center ${
isComplete ? 'bg-success' : 'bg-white'
}`}
onClick={toggleCompletionState}
>
这是播放音频文件的按钮,并确保在主进程和呈现器(在我的例子中是"ASSET")中设置相同的协议路径 如果有人有更好的方法或更好的方法,请在 comments 中回答.