简体   繁体   English

播放/暂停按钮无法正常工作 // React // wavesurfer.js

[英]play / pause button not working properly // React // wavesurfer.js

I have been struggling for HOURS trying to beat this, but i can´t do it.我一直在努力争取 HOURS 试图打败它,但我做不到。

The problem down below have a BUTTON, which has a child of an FontAwesomeIcon component.下面的问题有一个 BUTTON,它有一个 FontAwesomeIcon 组件的子组件。 i want the icon to change, is audio playing?我想改变图标,正在播放音频吗? then display the pause icon, if not.. you get the rest.然后显示暂停图标,如果没有.. 你得到 rest。

However, when i click the play button, it changes the icon as expected, and the audio plays.但是,当我单击播放按钮时,它会按预期更改图标,并播放音频。 when i click it again, this is when the problem occurs.当我再次单击它时,这就是问题发生的时候。 It will not pause the music, and it will certainly not change the icon back.它不会暂停音乐,当然也不会变回图标。

Can someone help me figure this out?有人可以帮我解决这个问题吗?

    import React from 'react';
import { useState, useRef, useEffect } from 'react';
import wavesurfer from 'wavesurfer.js';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

import { faCirclePlay, faCirclePause } from "@fortawesome/free-solid-svg-icons";





const AudioVisualizer = (props) => {
    const audioRef = useRef(null);
    // const [playing, setPlay] = useState(null);
    const [isClicked, setIsClicked] = useState(false)
    const [volume, setVolume] = useState(0.5);

    const [isBtnClicked, setBtnClicked] = useState(false)
    const [icon, setIcon] = useState(faCirclePlay);




    let audioTrack;

    useEffect(()=>{
        if (audioRef.current){
                audioTrack = wavesurfer.create({
                container: audioRef.current,
                progressColor: "#13AEA2",
                waveColor: "#eeee",
                cursorColor: "OrangeRed",
                preload: true,
                backend: "MediaElement",
                barWidth: 2,
                barHeight: 1, // the height of the wave
                fillParent: true,
                hideScrollbar: true,
                responsive: true,
                
            });
            audioTrack.load(props.audio);

        

            // audioTrack.load(props.audio);
        }
    }, [])   
    





    const onVolumeChange = e => {
        const { target } = e;
        const newVolume = +target.value;
        
    
        if (newVolume) {
            console.log("new volume true,,, volume: " + volume)
            setVolume(volume => newVolume);
            audioTrack.current.setVolume(newVolume || 1);
        }
    };



    const clicking =  (e) => {
        // Get a view of what the "click" registers:
        console.log(e.currentTarget.tagName);
        console.log(e.target);
        
        // if plying == pause
        if ( ! audioTrack.isPlaying() ) {
            console.log("not playing.. Start playing");
            audioTrack.play()
            setIcon(icon => faCirclePause)
            return

        } 


        console.log("Is playing.. will pause")
        audioTrack.play()
        setIcon(faCirclePlay);
        
        return
        
    
    };
    // FontAwesomeIcon => onClick change icon + pause/play audio. 
    
    return (
        <>
            <div  className='audio'  ref={audioRef}>
            </div> 
            <div className='audioKnobs'>
                
                <button  className='playpausewrapper' onClick={clicking}>
                        <FontAwesomeIcon className='playButton' icon={icon} />
                </button>

                <input type="range" id="volume" name="volume" min="0.01" max="1" step=".025" onChange={onVolumeChange} defaultValue={volume}/>
            </div>
        </>
    )
}


export default AudioVisualizer;

Error from console:来自控制台的错误: Img 显示了一些代码和本地主机预览和控制台..

AudioVisualizer.js:75 Uncaught TypeError: Cannot read properties of undefined (reading 'isPlaying')
    at clicking (AudioVisualizer.js:75:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
    at invokeGuardedCallback (react-dom.development.js:4277:1)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:1)
    at executeDispatch (react-dom.development.js:9041:1)
    at processDispatchQueueItemsInOrder (react-dom.development.js:9073:1)
    at processDispatchQueue (react-dom.development.js:9086:1)
    at dispatchEventsForPlugins (react-dom.development.js:9097:1)
    at react-dom.development.js:9288:1

Everything inside of a component is run every render.组件内部的所有内容都会在每次渲染时运行。 Components can rerender thousand of times.组件可以重新渲染数千次。

You are declaring a variable every render:您在每次渲染时声明一个变量:

let audioTrack;

But you are assigning the value only once但是您只分配一次

useEffect(()=>{
        if (audioRef.current){
                audioTrack = wavesurfer.create({
                container: audioRef.current,
                progressColor: "#13AEA2",
                waveColor: "#eeee",
                cursorColor: "OrangeRed",
                preload: true,
                backend: "MediaElement",
                barWidth: 2,
                barHeight: 1, // the height of the wave
                fillParent: true,
                hideScrollbar: true,
                responsive: true,
                
            });
            audioTrack.load(props.audio);

        

            // audioTrack.load(props.audio);
        }
    }, [])

You can't use normal variables like that.你不能使用这样的普通变量。

You have to use ref你必须使用ref

At the beginning of the component:在组件的开头:

const audioTrackRef = useRef(undefined);

In the useEffect在使用useEffect

audioTrackRef.current = wavesurfer.create({
                container: audioRef.current,
                progressColor: "#13AEA2",
                waveColor: "#eeee",
                cursorColor: "OrangeRed",
                preload: true,
                backend: "MediaElement",
                barWidth: 2,
                barHeight: 1, // the height of the wave
                fillParent: true,
                hideScrollbar: true,
                responsive: true,
                
            });

And in every other place在其他所有地方

audioTrackRef.current

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM