You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何停止正在播放的MP3?Electron+sound-play播放器遇停止难题

解决sound-play无法停止音频的问题

sound-play模块本质是调用系统原生音频播放命令(如Windows的wmplayer、macOS的afplay),启动后会生成独立的系统进程,但模块本身并未封装停止/终止该进程的API,因此无法直接通过它提供的方法停止播放。

下面给出两种适配Electron场景的替代方案:

方案1:在渲染进程中使用HTML5 Audio API(推荐)

Electron渲染进程支持完整的HTML5特性,直接用Audio对象可轻松实现播放、暂停、停止功能:

// 初始化音频对象
const audio = new Audio('file.mp3');

// 开始播放
audio.play().catch(err => console.error('播放失败:', err));

// 停止播放(暂停并重置到音频开头)
function stopAudio() {
  audio.pause();
  audio.currentTime = 0;
}

方案2:在主进程中使用play-sound模块

如果需要在主进程处理音频播放,可使用play-sound模块,它会返回播放进程实例,允许主动终止:

  1. 安装模块:
npm install play-sound
  1. 核心代码:
const player = require('play-sound')({});
let currentPlayProcess;

// 播放音频
function playAudio(filePath) {
  // 若已有播放进程,先停止
  if (currentPlayProcess) {
    currentPlayProcess.kill();
  }
  currentPlayProcess = player.play(filePath, (err) => {
    if (err) console.error('播放出错:', err);
    currentPlayProcess = null; // 播放结束后清空引用
  });
}

// 停止音频
function stopAudio() {
  if (currentPlayProcess) {
    currentPlayProcess.kill();
    currentPlayProcess = null;
  }
}

内容的提问来源于stack exchange,提问作者Pro Medya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 15:22:05