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

如何在Flutter Web中不依赖三方包跨平台播放系统声音?已试SystemSound无效

Flutter Web 无三方包实现系统声音播放

Flutter 官方的 SystemSound.play(SystemSoundType.alert) 在 Web 平台上没有实现——Web 沙箱环境没有提供统一的系统声音调用接口,因此调用后不会有任何声音输出。以下是两种无需三方包的实现方案:

方案一:用 Web Audio API 生成提示音

通过 Dart 调用 Web Audio API 直接生成简单提示音,无需依赖外部音频文件:

import 'dart:js' as js;

void playBeepSound() {
  // 兼容不同浏览器的 AudioContext 前缀
  final audioContext = js.JsObject(js.context['AudioContext'] ?? js.context['webkitAudioContext']);
  if (audioContext == null) {
    print('当前浏览器不支持 Web Audio API');
    return;
  }

  // 创建振荡器(生成声音波形)和增益节点(控制音量)
  final oscillator = audioContext.callMethod('createOscillator');
  final gainNode = audioContext.callMethod('createGain');

  // 连接音频链路:振荡器 → 增益节点 → 系统音频输出
  oscillator.callMethod('connect', [gainNode]);
  gainNode.callMethod('connect', [audioContext['destination']]);

  // 设置声音参数:正弦波、800Hz 频率
  oscillator['type'] = 'sine';
  oscillator['frequency']['value'] = 800;

  // 设置音量(取值范围 0~1)
  gainNode['gain']['value'] = 0.3;

  // 播放声音,200ms 后自动停止
  oscillator.callMethod('start');
  js.context.callMethod('setTimeout', [() => oscillator.callMethod('stop'), 200]);
}

方案二:利用浏览器通知提示音

通过浏览器 Notification API 触发系统通知,同时播放默认通知提示音(需用户授权通知权限):

import 'dart:html' as html;

Future<void> playNotificationAlert() async {
  // 请求用户授权通知权限
  final permissionStatus = await html.Notification.requestPermission();
  if (permissionStatus != 'granted') {
    print('用户未授权通知权限,无法播放提示音');
    return;
  }

  // 创建通知,使用浏览器默认提示音
  final notification = html.Notification('操作提示', html.NotificationOptions(
    body: '已完成指定操作',
    // 若需自定义音频,可传入项目静态资源 URL,如 sound: 'assets/alert.mp3'
  ));

  // 通知关闭后清理资源
  notification.onClose.listen((_) => notification.remove());
}

注意事项

  • Web 环境无法直接访问操作系统原生系统声音(如 Windows/Mac 自带提示音),上述方案均基于浏览器自身音频能力实现。
  • 方案二中的自定义音频需确保可跨域访问,或放置在项目静态资源目录内。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 16:40:41