pmndrs / drei

🥉 useful helpers for react-three-fiber
https://docs.pmnd.rs/drei
MIT License
8.27k stars 682 forks source link

PositionalAudio issue #504

Open Russo-creation opened 3 years ago

Russo-creation commented 3 years ago

Problem description:

I noticed that PositionalAudio component not playing sound even on storybook https://drei.pmnd.rs/?path=/story/abstractions-positionalaudio--positional-audio-scene-st.

I followed https://codesandbox.io/s/r3f-drei-positionalaudio-forked-khx5p?file=/src/index.js:442-527 and sometimes sound on sample codesandbox works (when focused on codesandbox iframe from beginning).

I don't think it is related with autoplay policy https://sundaykuloksun.medium.com/video-play-not-working-html5-autoplay-policy-beed81d64ca5 but more like a bug.

Relevant code:

import { PositionalAudio } from "@react-three/drei";
...
 <mesh>
          <boxBufferGeometry attach="geometry" />
          <meshBasicMaterial attach="material" color="hotpink" />
          <PositionalAudio
            url="/assets/audio/ice_cream_music.mp3"
            distance={1}
            loop
          />
</mesh>

Suggested solution:

Using suggested code from https://codesandbox.io/embed/r3f-positional-audio-246wl works fine.

import React, { Suspense, useRef, useEffect, useState } from "react";
import { useThree, useLoader } from "@react-three/fiber";
...
  function Sound({ url }) {
    const sound = useRef();
    const { camera } = useThree();
    const [listener] = useState(() => new THREE.AudioListener());
    const buffer = useLoader(THREE.AudioLoader, url);
    useEffect(() => {
      sound.current.setBuffer(buffer);
      sound.current.setRefDistance(1);
      sound.current.setLoop(true);
      sound.current.play();
      camera.add(listener);
      return () => camera.remove(listener);
    }, []);
    return <positionalAudio ref={sound} args={[listener]} />;
  }
...
<mesh>
          <boxBufferGeometry attach="geometry" />
          <meshBasicMaterial attach="material" color="hotpink" />
          <Sound url="/assets/audio/ice_cream_music.mp3" />
</mesh>
joshuaellis commented 3 years ago

@drcmda you did some fixes on this component if I remember correctly? Would you mind looking at this 🙏🏼

robksawyer commented 2 years ago

Any news? I'm not able to get this working either.

ashleyjamesbrown commented 2 years ago

what about using more than one <Sound url = "" />

When i do i get errors and only one sound will play ? Any thoughts

Ruchita1010 commented 1 year ago

I'm facing the issue! Is there any other workaround for this apart from the "Sound" function?