大家好,很高兴又见面了,我是"高级前端进阶",由我带着大家一起关注前端前沿、深入前端底层技术,大家一起进步,也欢迎大家关注、点赞、收藏、转发!
1.什么是 react-sounds
react-sounds 用于为 React 应用添加音效 ,其提供了一个可立即播放的音效库,具有简单的 API、延迟加载和离线支持。其核心特性包括:
- 丰富的库:访问按类别(UI、通知、游戏等)整理的精选声音
- 轻量级:软件包中仅包含 JS 封装器,音频文件托管在 CDN 上,以减少打包体积
- 延迟加载:仅在需要时高效获取声音,从而提升初始加载性能
- 离线支持:使用内置的 CLI 工具轻松下载并打包声音,实现自托管
- 简洁的 API:使用易于使用的钩子函数(如 useSound)和组件(如 SoundButton)轻松集成声音
- 可配置:自定义 CDN URL、预加载声音、全局启用 / 禁用声音以及控制播放选项
目前 react-sounds 在 Github 通过 MIT 协议开源,是一个值得关注的前端开源项目。
2.如何使用 react-sounds
2.1 使用 useSound Hook 播放声音
useSound Hook 是与声音交互的主要方式,比如下面的例子:
import { useSound } from "react-sounds";
function Button() {
const { play } = useSound("ui/button_1");
return <button onClick={() => play()}>Click Me</button>;
}
开发者还可以自定义声音文件:
import { useSound } from "react-sounds";
import customClickSound from "../assets/sounds/click.mp3";
function Button() {
// 直接导入自定义的音频文件
const { play } = useSound(customClickSound);
return <button onClick={() => play()}>Custom Sound Button</button>;
}
当然,如果只是用于简单的一次性声音播放则无需状态或控制,直接使用 playSound 即可:
import { playSound } from "react-sounds";
import customSound from "../assets/sounds/notification.mp3";
function Button() {
// 使用内置声音
const handleClick = () => playSound("ui/button_1");
// 自定义声音
const handleCustomSound = () => playSound(customSound);
return (
<div>
<button onClick={handleClick}>Built-in Sound</button>
<button onClick={handleCustomSound}>Custom Sound</button>
</div>
);
}
但是,为了获得最佳效果,开发者可以使用 SoundProvider 组件包装应用。这样可以控制声音启用状态、预加载声音并建立声音上下文:
import { SoundProvider } from "react-sounds";
import customSound from "../assets/sounds/startup.mp3";
function App() {
return (
<SoundProvider
// 可选:预加载内置和自定义声音
preload={["ui/button_click", "notification/success", customSound]}
// 可选:设置初始声音启用状态(默认为 true)
initialEnabled={true}
>
<YourApp />
</SoundProvider>
);
}
2.2 自定义声音选项
开发者还可以使用各种选项自定义声音播放配置,比如:
import { useSound, playSound, SoundOptions } from "react-sounds";
import customExplosion from "../assets/sounds/explosion.mp3";
// SoundOptions interface:
// {
// volume?: number; // 0.0 to 1.0
// rate?: number; // playback speed (1.0 is normal)
// loop?: boolean; // whether to loop the sound
// }
function SoundPlayer() {
const { play } = useSound(customExplosion);
const playWithOptions = () => {
// 设置自定义配置
play({
volume: 0.8, // 80% volume
rate: 1.2, // 20% faster
loop: false, // don't loop
});
// 使用特定配置直接播放
playSound("ui/click", { volume: 0.5 });
};
return <button onClick={playWithOptions}>Play with Options</button>;
}
同时,react-sounds 还提供了声音启用/禁用能力,该设置会自动保存在 localStorage 中:
import { setSoundEnabled, isSoundEnabled } from "react-sounds";
// 判断声音是否启动
const enabled = isSoundEnabled();
// 禁用声音
setSoundEnabled(false);
// 启用声音
setSoundEnabled(true);
参考资料
https://github.com/aediliclabs/react-sounds
https://www.reactsounds.com/docs
https://www.reactsounds.com/sounds