正在反应组件内调用暂停功能,但没有任何反应

时间:2020-12-28 15:39:26

标签: javascript reactjs howler.js

我有一个用于播放和暂停的切换按钮。 这是代码:

export default (props) => {
  let [soundState, setSoundState] = useState({ state: 'off' })
  let [soundId, setSoundId] = useState(null)
  let [soundSeek, setSoundSeek] = useState(null)
  var sound = new Howl({
    src: [props.url],
    html5: true,
    volume: 1,
    myMusicID: '',
    saveSeek: null,
    onpause: () => {
      console.log('pause', soundId)
    }
  })

  const onPlayHandle = () => {
    setSoundState({ state: 'playing' })
    let id = sound.play()
    setSoundId(id)
    sound.seek(soundSeek, soundId)
  }
  const onPauseHandle = () => {
    console.log('onPauseHandle', soundId)
    sound.pause(soundId)
    setSoundSeek(sound.seek(soundId))
  }
 
}

onpause 已触发但声音仍在运行...

请帮忙...

1 个答案:

答案 0 :(得分:2)

每次您的组件被渲染时,都会创建一个新的 Howl 实例。您需要使用 useRef 来保留实例引用:

const soundRef = useRef(new Howl({
    src: ["http://listen.vo.llnwd.net/g3/prvw/6/5/8/3/1/2255913856.mp3"],
    html5: true,
    volume: 1,
    myMusicID: "",
    saveSeek: null,
    onpause: () => {
      console.log("pause", soundId);
    }
  }));
const sound = soundRef.current;