zmxv / react-native-sound

React Native module for playing sound clips
MIT License
2.78k stars 748 forks source link

Sound never plays again once I release it, even on component re-load #785

Open cgruca opened 2 years ago

cgruca commented 2 years ago

:beetle: Description

I want to play some music when user loads into the app and stays on a specific screen. I can get the track to play at the start however, once they leave the screen and come back to it later, the sound doesn't play anymore. Any help would be appreciated, thanks.

:beetle: What have you tried? Changing tracks, different methods of playing audio etc.

//audio setup outside of component function
var Sound = require('react-native-sound');

var background = new Sound('onboarding.mp3', Sound.MAIN_BUNDLE, (error) => {
  if (error) {
      console.log('failed to load the sound', error);
      return;
    } else {
      background.play((success)=> console.log(success)); // have to put the call to play() in the onload callback
  }
  });

//then playing tracks with following in useEffect
background.setVolume(1);

background.play(success => {
  if (success) {
    console.log('successfully finished playing');
  } else {
    console.log('playback failed due to audio decoding errors');
  }
});

//then I run this after component unmounts
background.stop(() => {});
background.release();

Is your issue with...

Are you using...

Which versions are you using?

Does the problem occur on...

If your problem is happening on a device, which device?

rheng001 commented 2 years ago

@cgruca Where you are able to solve this problem?

cgruca commented 2 years ago

nope, i just never release it

On Tue, May 24, 2022, 5:53 PM Richard Heng @.***> wrote:

@cgruca https://github.com/cgruca Where you are able to solve this problem?

— Reply to this email directly, view it on GitHub https://github.com/zmxv/react-native-sound/issues/785#issuecomment-1136173203, or unsubscribe https://github.com/notifications/unsubscribe-auth/AJQJIEFRARDXZW5H5VHIUWTVLUCOZANCNFSM5QOJJNRQ . You are receiving this because you were mentioned.Message ID: @.***>

rheng001 commented 2 years ago

I figured out the same thing, never releasing works. Thanks for confirming!

rawatnaresh commented 1 year ago

Initializing them outside the component and releasing them on component un-mount will not work. you have to initialize them during component mount.

import { useEffect } from 'react';
import { Button } from 'react-native';

export const Sound = require('react-native-sound');
Sound.setCategory('Playback');

let mySound;

export const MyComp = () => {
  useEffect(() => {
    mySound = new Sound('mysound.mp3', Sound.MAIN_BUNDLE);

    return () => {
      mySound.stop();
      mySound.release();
    };
  }, []);

  return (
    <Button
      title={'Play'}
      onPress={() => {
        mySound.play();
      }}
    />
  );
};