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

Next.js部署至Vercel报错:ReferenceError: Audio is not defined

Next.js 音频组件部署Vercel出错的解决方案

问题根源

本地运行正常但Vercel部署失败,核心原因是音频文件路径引用错误。本地开发服务器会直接映射public目录到根路径,相对路径depeche.mp3能正常解析;但Vercel部署后静态资源会被优化分发,相对路径无法正确寻址到音频文件。

修复步骤

1. 规范静态资源存放

把depeche.mp3放到项目根目录的public文件夹下(没有就新建),这是Next.js存放静态资源的标准位置。

2. 修正音频路径

将Audio实例的路径改为绝对路径(以/开头),确保部署后能正确访问:

const [audio] = useState(new Audio('/depeche.mp3'));

3. 优化组件(推荐)

用useRef和useEffect管理Audio实例,避免组件重复渲染时重复创建实例,同时在组件卸载时清理资源:

'use client';
import React, { useState, useEffect, useRef } from 'react';
import { GiEasterEgg } from 'react-icons/gi';
import { AiFillPauseCircle } from 'react-icons/ai';

const Music = () => {
  const [isPlaying, setIsPlaying] = useState(false);
  const audioRef = useRef(null);

  useEffect(() => {
    // 初始化音频实例
    audioRef.current = new Audio('/depeche.mp3');
    // 组件卸载时暂停并清理音频
    return () => {
      if (audioRef.current) {
        audioRef.current.pause();
        audioRef.current = null;
      }
    };
  }, []);

  const playSound = () => {
    audioRef.current?.play();
    setIsPlaying(true);
  };

  const pauseSound = () => {
    audioRef.current?.pause();
    setIsPlaying(false);
  };

  return (
    <div>
      {isPlaying ? (
        <button onClick={pauseSound}>
          <AiFillPauseCircle className='text-5xl text-white' />
        </button>
      ) : (
        <button onClick={playSound}>
          <GiEasterEgg className='text-5xl text-white' />
        </button>
      )}
    </div>
  );
};

export default Music;

4. 检查Vercel部署配置

默认情况下Vercel会自动处理Next.js的public目录,无需额外配置。如果有自定义vercel.json,确认没有排除public目录的规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 11:42:50