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

使用ReactJs实现页面加载时自动播放一次mp3音效的方法是什么?

React 首次加载自动播放 MP3 音效实现方案

现有代码问题梳理

  • useSound 是 React 专属 Hook,只能在函数组件的顶层作用域调用,你当前写在组件外部的写法不符合 Hook 使用规则,会直接触发语法报错。
  • 你调用了两次 render 方法挂载内容,正常 React 单页应用仅需要一个根入口挂载所有内容,无需拆分两次挂载。
  • 你已经通过 import 引入了 mp3 资源,调用 useSound 时直接传入引入的变量即可,不需要传字符串路径。

修正后可运行代码

import React, { useEffect } from 'react';
import { render } from 'react-dom';
import './styles.scss';
import sun from "/src/Images/cuteMovingSun.gif"
import hereComesTheSun from '/src/Images/HereComesTheSunEdit.mp3'
import useSound from 'use-sound';

const Title = () => {
  return <div>Good Morning, Sunshine!</div>;
};

// 统一的根组件
const App = () => {
  const [play] = useSound(hereComesTheSun);

  // 空依赖数组代表仅在组件首次挂载完成后执行1次
  useEffect(() => {
    play();
  }, []);

  return (
    <>
      <Title />
      <img className="sun" src={sun} alt="移动的太阳" />
    </>
  )
}

// 仅调用一次render挂载根组件
render(<App />, document.getElementById('root'));

你可以把原HTML里的mySun节点删掉,所有内容都挂载到root节点即可。

注意事项

当前绝大多数主流浏览器为了避免用户被无预警的声音骚扰,默认禁止没有用户交互行为的有声媒体自动播放,上述自动播放逻辑如果在用户没有点击/触碰过页面的情况下触发,大概率会被浏览器拦截。如果需要保证播放成功率,可以额外加一个引导用户点击的按钮,把play()的触发逻辑绑定到按钮的点击事件上。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 06:54:02