Skip to main content

useAudioData()

@remotion/media-utils 工具函数包的一部分。

🌐 Part of the @remotion/media-utils package of helper functions.

这个便捷函数将 getAudioData() 函数封装到一个钩子中,并执行三件事:

🌐 This convenience function wraps the getAudioData() function into a hook and does 3 things:

  • 保持音频数据处于某种状态
  • 将函数封装在 delayRender() / continueRender() 模式中。
  • 处理在获取数据过程中组件被卸载并抛出 React 错误的情况。

使用此函数,你可以根据音频属性优雅地渲染一个组件,例如可以与 visualizeAudio() 函数一起使用。

🌐 Using this function, you can elegantly render a component based on audio properties, for example together with the visualizeAudio() function.

info

远程音频文件需要支持 CORS

更多信息

参数

🌐 Arguments

src

指向音频资源的字符串。

🌐 A string pointing to an audio asset.

返回值

🌐 Return value

AudioData | null - 一个包含音频数据的对象(参见 getAudioData() 的文档)或 null,如果数据尚未加载。

示例

🌐 Example

import {useAudioData} from '@remotion/media-utils';
import {staticFile} from 'remotion';

export const MyComponent: React.FC = () => {
  const audioData = useAudioData(staticFile('music.mp3'));

  if (!audioData) {
    return null;
  }

  return <div>This file has a {audioData.sampleRate} sampleRate.</div>;
};

错误

🌐 Errors

如果你传入一个没有音频轨道的文件,这个钩子将抛出一个错误(从 v4.0.75 开始)或导致未处理的拒绝(直到 v4.0.74)。

🌐 If you pass in a file that has no audio track, this hook will throw an error (from v4.0.75) or lead to an unhandled rejection (until v4.0.74).

要确定文件是否有音频轨道,可以在服务器上使用 getVideoMetadata() 函数,如果文件没有音频轨道则拒绝该文件。为此,请检查 audioCodec 字段是否为 null

🌐 To determine if a file has an audio track, you may use the getVideoMetadata() function on the server to reject a file if it has no audio track. To do so, check if the audioCodec field is null.

如果你想在组件中捕捉错误,你需要通过从此页面底部获取源代码来制作你自己的内联钩子。

🌐 If you want to catch the error in the component, you need to make your own inline hook by taking the source code from the bottom of this page.

另请参阅

🌐 See also