reactjs 在React中显示音频波形

rkue9o1l  于 2023-02-15  发布在  React
关注(0)|答案(1)|浏览(371)

所以我建了这个网页,它允许用户上传一首歌,然后在主页上以卡片的形式显示。有点像Soundcloud...
我刚刚开始学习React,从html,css和JS后,所以请理解我的新这一切。
我已经研究了这个主题很多,似乎没有人为我工作。
我一直在尝试howler.js和wavesurfer.js,没有任何显示波形的运气。
以前有没有人试过这样做?,有没有人能帮上忙?

import { ErrorResponse } from '@remix-run/router';
import React from 'react'
import wavesurfer from 'wavesurfer.js'
import "./css/audio.css"
import { useRef } from 'react';

export const AudioVisualizer = (props) => {
// the homepage has a function to map through all the objects     in the 
// database, and in return i get every object. I then get the link from each
// object and pass this link into this function as an ARgument. 
let link = props; 
const audioRef = useRef();
console.log("here is props:  " + link);

try {

var audioTrack = wavesurfer.create({
    container: audioRef,
    wavecolor: "#eee",
    progressColor: "red",
    barWidth: 2,
});

audioTrack.load(link);
} catch (ErrorResponse)  {
    console.error("Something happened..");
    return ErrorResponse;
};

return (
    <div className='audio' ref={audioRef}>

    </div>
)

}
从那里我有一个实际的Home.js页面,我想在那里显示从上面的函数返回的。
home.js文件如下所示:

import React, { useEffect, useState } from 'react';
import '../components/css/home/home.css';
import {collection, getDocs, onSnapshot} from 'firebase/firestore';
import {db} from '../firebase'
import { useNavigate } from 'react-router-dom';
import {ClipLoader} from 'react-spinners';
import {AudioVisualizer} from "../components/audioVisualizer"

const Home = () => {
const [songs, setSongs] = useState([]);
const [loading, setLoading] = useState(false);
const navigate = useNavigate();

useEffect(() => {
    setLoading(true);
    const retrieveSongs = onSnapshot(
        collection(db, "songs"), 
        (snapshot) => {
            let arrayList = [];
            snapshot.docs.forEach((doc) => {
                arrayList.push({ id: doc.id, ...doc.data() });
            });
            setSongs(arrayList);
            setLoading(false);

        }, 
        (error) => {
            console.log(error);
        }
    );

    return () => {
        retrieveSongs();
    };
    
}, []);

return (
    <div className='home_wrapper'>
        <>
        
            {loading ? 
                <ClipLoader color="#36d7b7" />
            :

                <div className='homepage_container'>

                    {   songs.map((data) => {
                        return (
                            <article key={data.id} className='card'>
                                <div className='card_content'>
                                    <img className='card_image' src={data.image} />

                                    <div className='song_info'>
                                    <h2>{data.title}</h2>
                                    <h4>{data.artist}</h4>
                                    </div>

                                    <div className='audioplayer'>
                                    {AudioVisualizer(data.audio)}
                                    {/* <ReactAudioPlayer src={data.audio} autoPlay controls/> */}
                                    {/* <Waveform className="audio_file" audio={data.audio}/> */}
                                    </div>

                                </div>

                                <div className='card_content_extra'>
                                    <button onClick={() => navigate('/update/${data.id}')}>Edit</button>
                                    <button >Listen</button>
                                </div>

                                {/* <div id="waveform"></div>
                                    <button class="btn btn-primary" onclick="wavesurfer.playPause()">
                                    <i class="glyphicon glyphicon-play"></i>Play/Pause
                                    </button> */}
                            </article>
                        )
                    })}
                </div>
            }
        </>
    </div>
)

}

export default Home

更新:
正如我在评论中所描述的。当我从数据库Map歌曲对象时,波形不会显示。当我传递一个直接链接到组件时,它会工作。但当我传递对象“audio”并获得值时,它不会显示波形。当我尝试console.log(data.audio)//时,它返回undefined。
你自己看看:As you can see from the console.log, it acts weird..

f87krz0w

f87krz0w1#

对DOM元素的引用由.current属性访问,而不是由React创建的引用对象。
您可以使用useEffect钩子来加载数据。
然后以JSX react方式创建AudioVisualizer组件,并将链接传递给wavesurfer。
另外,wavesurfer dom对象需要有一定的大小。
请看这个小例子:

import React from 'react';
import ReactDOM from 'react-dom/client';
import { useRef, useEffect } from 'react';
import wavesurfer from 'wavesurfer.js'

const AudioVisualizer = (props) => {

  const audioRef = useRef();

  useEffect(()=>{
    if (audioRef.current){
      let audioTrack = wavesurfer.create({
          container: audioRef.current,
      });
      audioTrack.load(props.link);
    }
  })

  return <div style={{minWidth: "200px"}} className='audio' ref={audioRef}></div> 
}

function App(props) {
  return (
    <div className='App'>
      <AudioVisualizer link={"https://actions.google.com/sounds/v1/science_fiction/creature_distortion_white_noise.ogg"}></AudioVisualizer>
    </div>
  );
}

ReactDOM.createRoot( 
  document.querySelector('#root')
).render(<App />)

相关问题