簡體   English   中英

反應音頻無法設置未定義的屬性“音量”

[英]React audio Cannot set property 'volume' of undefined

我正在嘗試使用 Audio 元素播放 mp3,但每當播放器呈現錯誤時:- 無法設置未定義的屬性“音量”。

Play prop 只是一個布爾值。

useRef() current 屬性在我 console.log 時向我顯示 mp3 文件。

我刪除了 volume 屬性,但隨后它顯示了與 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;

我做錯了什么?

這部分代碼:

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

在 React 甚至有機audioRef.current設置為 Audio 元素之前,它會立即被調用。 你的函數還沒有完成渲染,React 甚至不知道在哪里使用了audioRef

動議一段代碼成useEffect ,或更好的是,取代您audioRef用的回調函數(其仍可以存儲在另一個ref或狀態變量的音頻組件),如圖所示在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM