javascript 如何使用React use-sound模块停止音频?

ny6fqffe  于 2022-12-28  发布在  Java
关注(0)|答案(2)|浏览(206)

我正在使用React中的use-sound模块,并尝试制作一个播放/暂停按钮。当我单击按钮时,音频会播放,但当我再次单击按钮时,无法停止音频。
我在控制台中检查,看到单击按钮正确地更改了isPlaying值,但实际的音频并没有停止。
有人知道怎么关掉音频吗?非常感谢!
下面是我的按钮代码,“music”变量是音频文件的路径:

import React from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import useSound from "use-sound";

const PlayBtn = ({ music }) => {
  const sound = music;
  const [play, { stop, isPlaying }] = useSound(sound);
  console.log(isPlaying);

  return (
    <span>
      <FontAwesomeIcon
        icon={["far", "play-circle"]}
        onClick={isPlaying ? stop : play}
      />
    </span>
  );
};

export default PlayBtn;
2izufjch

2izufjch1#

这将帮助你,音频播放和暂停使用挂钩。只是编辑和编写功能,根据您的代码

import React, { useState, useEffect } from "react";
    
    const useAudio = url => {
      const [audio] = useState(new Audio(url));
      const [playing, setPlaying] = useState(false);
    
      const toggle = () => setPlaying(!playing);
    
      useEffect(() => {
          playing ? audio.play() : audio.pause();
        },
        [playing]
      );
    
      useEffect(() => {
        audio.addEventListener('ended', () => setPlaying(false));
        return () => {
          audio.removeEventListener('ended', () => setPlaying(false));
        };
      }, []);
    
      return [playing, toggle];
    };
    
    const Player = ({ url }) => {
      const [playing, toggle] = useAudio(url);
    
      return (
        <div>
          <button onClick={toggle}>{playing ? "Pause" : "Play"}</button>
        </div>
      );
    };
    
    export default Player;
iq0todco

iq0todco2#

中断use-sound包版本4.0删除了isPlaying布尔值;跟踪该状态会导致额外的重新呈现,当使用钩子的多个示例时,这些重新呈现可能会堆积起来。
如果您依赖于此属性,则可以使用Howler中的onplayonend事件自己实现它。

样品

import React from "react";
import useSound from 'use-sound';
import Music from '../assets/audio/Music.mp3';

const MusicPlayer = () => {
  const [isPlaying, setIsPlaying] = React.useState(false);

  const [playBoop, {pause}] = useSound(Music, {
    onplay: () => setIsPlaying(true),
    onend: () => setIsPlaying(false),
  });

  const togglePlay = () => {
    if (isPlaying) {
      pause();
    } else {
      playBoop();
    }
    setIsPlaying(!isPlaying);
  }

  return (
    <>
      <h2>Is playing: {isPlaying.toString()}</h2>
      <br />
      <button onClick={togglePlay}>Play sound</button>
    </>
  );
};

export default MusicPlayer;

相关问题