【问题标题】:React audio Cannot set property 'volume' of undefined反应音频无法设置未定义的属性“音量”
【发布时间】:2021-07-25 14:50:34
【问题描述】:

我正在尝试使用 Audio 元素播放 mp3,但每当播放器呈现错误时:- 无法设置未定义的属性“音量”。

Play 属性只是一个布尔值。

当我 console.log 时,useRef() 当前属性会显示 mp3 文件。

我删除了音量属性,但随后它显示 audio.play() 的相同错误。

为什么音频未定义?

import React, { useState, useRef } from "react";
import "../../Static/player.css";
import Nowplaying from "./Nowplaying";
import SongInfo from "./SongInfo";
import Slider from "./Slider";
import Duration from "./Duration";
import song from "../../Static/assets/song.mp3";

const Player = (props) => {

  const { Play } = props;

  const [percentage, setPercentage] = useState(0)
  const [duration, setDuration] = useState(0)
  const [currentTime, setCurrentTime] = useState(0)

  const audioRef = useRef()


  const onChange = (e) => {
    const audio = audioRef.current
    audio.currentTime = (audio.duration / 100) * e.target.value
    setPercentage(e.target.value)
  }


  const play = () => {
    const audio = audioRef.current
    audio.volume = 0.1

    if (!Play) {
      audio.play()
    }

    if (Play) {
      audio.pause()
    }
  }

  const getCurrDuration = (e) => {
    const percent = ((e.currentTarget.currentTime / e.currentTarget.duration) * 100).toFixed(2)
    const time = e.currentTarget.currentTime

    setPercentage(+percent)
    setCurrentTime(time.toFixed(2))
  }

  if (Play) {
    play();
  } else {
    play();
  }

  return (
    <div className="player-screen">
      <div className="play-screen">
        <div className="navbar">
          <Nowplaying />
        </div>
        <div className="song-info">
          <SongInfo />
        </div>
        <div className="player-controls">
          <Slider percentage={percentage} onChange={onChange} />
          <Duration
            duration={duration}
            currentTime={currentTime}
          />
          <audio
            ref={audioRef}
            onTimeUpdate={getCurrDuration}
            onLoadedData={(e) => {
              setDuration(e.currentTarget.duration.toFixed(2));
            }}
            src={song}
          ></audio>
        </div>
      </div>
    </div>
  );
};

export default Player;

我做错了什么?

【问题讨论】:

  • 请添加检查以确保audio 不为空。阅读reactjs.org/docs/…,特别是上面写着“React 将在组件安装时将当前属性分配给 DOM 元素,并在卸载时将其分配回 null”的部分

标签: javascript reactjs html5-audio


【解决方案1】:

这部分代码:

  if (Play) {
    play();
  } else {
    play();
  }

在 React 甚至有机会将 audioRef.current 设置为 Audio 元素之前立即被调用。 你的函数还没有完成渲染,React 甚至不知道audioRef 的使用位置。

将那段代码移动到useEffect,或者更好的是,用回调函数替换你的audioRef(它仍然可以将音频元素存储在另一个引用或状态变量中),如here所示。

【讨论】:

  • 谢谢它的工作,我是新来的反应。你是正确的函数在它呈现之前被调用,这就是为什么当我在它已经呈现时放置代码但在我刷新它时给出错误时它工作的原因。谢谢。
猜你喜欢
  • 2019-01-31
  • 2023-03-11
  • 2021-06-21
  • 2012-12-14
  • 2021-03-03
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
相关资源
最近更新 更多