我在这里和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 中回答.

Node.js相关问答推荐

使用prisma迁移到SQL失败

如何从puppeteer的page. evaluate()中获取流数据?(node.js)

我的位置也移动时左右拖动谷歌 map

MongoDB-如何验证Document字段以仅允许特定的文件扩展名?

Firebase-admin筛选器.或只考虑第一个WHERE子句

如果我加入另一个公会且我的​​机器人已在其中,欢迎消息发送错误

Nestjs swc 错误:找不到模块项目路径/src/app.module

Express Web 服务器部署到 prod 但 GET 返回超时错误

Promise 和 Azure 语音转文本

SvelteKit应用程序立即退出,没有错误

错误 node :错误:绑定消息提供 16 个参数,但准备语句需要 15 个

Node.js 上的 CLI 应用程序如何通过 child_process 将选项值作为参数传递给 Shell 命令

无服务器部署使用无服务器组合抛出`spawn serverless ENOENT`

Winston http 日志(log)级别的行为与 info 不同

Socket IOFlutter 未连接

无法更新MongoDB中的文档:";伯森场';writeConcern.w';是错误的类型';数组'&引用;

如果我使用像 express 这样的 node 服务器,是否需要 webpack-dev-server

如何在 node 调试器中禁用第一行中断

Puppeteer:如何提交表单?

NPM:为什么要安装这个包?