zmxv / react-native-sound

React Native module for playing sound clips

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

cgruca opened this issue · comments

🪲 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.

🪲 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...

  • [ x] iOS
  • [x ] Android
  • Windows

Are you using...

  • [x ] React Native CLI (e.g. react-native run-android)
  • Expo
  • Other: (please specify)

Which versions are you using?

  • React Native Sound: "^0.11.1",
  • React Native: "0.63.4",
  • iOS: 15
  • Android: Oreo

Does the problem occur on...

  • [x ] Simulator
  • [x ] Device

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

  • Device: iphone 12, pixel 3

@cgruca Where you are able to solve this problem?

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

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();
      }}
    />
  );
};