我正在开发一个 React 前端,需要播放音频文件。我有一个后端服务,可以为我提供源自 WhatsApp 对话的
ogg
音频文件。它在 Android 浏览器/桌面 Chrome 中运行良好,但在 Safari 中则不然,因为 Safari 不支持。我只发现非常复杂的设置不能很好地与 React 配合使用,并且需要网络工作者和 wasm
进行解码。(例如 this 和 this)。这些答案是“有效的”,但我找不到(相对)简单的方法来实现这一点,以及更多 React 式的方法。
我认为最好使用像“howler.js”这样的库。 官方网站
优点是,通过此工具,您可以将“ogg”文件转换为“Mp3”,并且可以在任何类型的浏览器中播放。
首先安装“howler.js”
npm install howler
或
yarn add howler
然后创建 React 组件以将“ogg”文件发送到该组件并将其转换为“Mp3”
import React, { useEffect, useRef } from 'react';
import { Howl } from 'howler';
const AudioPlayer = ({ src }) => {
const soundRef = useRef(null);
useEffect(() => {
soundRef.current = new Howl({
src: [src],
format: ['ogg', 'mp3'], // specify the formats you are providing
});
return () => {
if (soundRef.current) {
soundRef.current.unload();
}
};
}, [src]);
const playAudio = () => {
if (soundRef.current) {
soundRef.current.play();
}
};
return (
<div>
<button onClick={playAudio}>Play Audio</button>
</div>
);
};
export default AudioPlayer;
之后将其导入到您的 main.jsx 或 app.jsx 中。