Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rickyansari/920f3bfc6c767ef1a078eb5e3f586cd0 to your computer and use it in GitHub Desktop.
Save rickyansari/920f3bfc6c767ef1a078eb5e3f586cd0 to your computer and use it in GitHub Desktop.
/* playing sound using react-native-sound.
We have a list of sounds and by default we are playing the first sound in the list.
In order to change the sound track a user can select the file name from the list.
Note:
1. Android: Save your sound clip files under the directory android/app/src/main/res/raw.
Note that files in this directory must be lowercase and underscored (e.g. my_file_name.mp3) and that subdirectories are not supported by Android.
2. iOS: Open Xcode and add your sound files to the project (Right-click the project and select Add Files to [PROJECTNAME])
*/
import React, {useEffect, useRef, useState} from 'react';
import {StyleSheet, Text, TouchableOpacity, View} from 'react-native';
var Sound = require('react-native-sound');
const soundFiles = ['whoose.mp3', 'track2.mp3', 'track3.mp3'];
const App: () => React$Node = () => {
const [currentTrackName, setCurrentTrackName] = useState(soundFiles[0]);
const currentSound = useRef(null);
useEffect(() => {
try {
const newSound = new Sound(
currentTrackName,
Sound.MAIN_BUNDLE,
(error) => {
if (error) {
console.log('ERROR ON LOAD', error);
return;
}
if (currentSound && currentSound.current) {
currentSound.current.release();
}
currentSound.current = newSound.play((success) => {
if (success) {
console.log('Sound Played Successfully');
} else {
console.log('unable to play Sound');
}
});
},
);
} catch (error) {
console.error(error);
}
() => {
if (currentSound && currentSound.current) {
currentSound.current.release();
}
};
}, [currentTrackName]);
return (
<View style={styles.body}>
{soundFiles.map((fileName, id) => (
<TouchableOpacity
key={fileName}
onPress={() => {
setCurrentTrackName(fileName);
}}
style={styles.track}>
<Text>{fileName}</Text>
</TouchableOpacity>
))}
</View>
);
};
const styles = StyleSheet.create({
body: {
flex: 1,
justifyContent: 'center',
flexDirection: 'row',
alignItems: 'center',
backgroundColor: 'yellow',
},
track: {
backgroundColor: 'gray',
margin: 4,
fontSize: 12,
fontWeight: '600',
padding: 4,
paddingRight: 12,
textAlign: 'right',
},
});
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment