zmxv / react-native-sound

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

Is there any audio puase/stop listener? #817

Open Robiullah2244 opened 1 year ago

Robiullah2244 commented 1 year ago

I have to update my component if the audio is stopped from another component.

sultson commented 1 year ago

Hi @Robiullah2244 - the library does not provide listeners, but you can accomplish this with useState() instead. Here's a small example of it, where the displayed text & button are dependent on whether audio is currently playing or not. Let me know if this fixes the issue for you!

App.tsx

import React, { useState } from 'react';
import { Text, View, Button, StyleSheet } from 'react-native';
import Sound from 'react-native-sound'

Sound.setCategory('Playback');
var whoosh = new Sound('whoosh.mp3', Sound.MAIN_BUNDLE, (error) => {
  if (error) {
    console.log('failed to load the sound', error);
    return;
  }
});

function App(): JSX.Element {
  const [playing, setPlaying] = useState(false)

  function toggleSound() {
    if (playing) {
      whoosh.stop(() => setPlaying(false))
    } else {
      setPlaying(true)
      whoosh.play((success) => {
        if (!success) { console.log('Playback failed due to decoding errors') }
        setPlaying(false)
      });
    }

  }

  return (
    <View style={styles.container}>
      <Text style={styles.text} >{playing ? 'Audio is currently playing' : 'Audio is stopped'}</Text>
      <Button title={playing ? 'stop' : 'play'} onPress={toggleSound} />

    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent:'center',
    alignItems:'center'
  },
  text: {
    fontSize:20,
    margin:10
  }
})

export default App;

Environment

package version
react-native 0.71.3
react-native-sound 0.11.2
BraveEvidence commented 1 year ago

This will help https://www.youtube.com/watch?v=vVI7ZAZq5e0