0

I have a really simple app, that has a button. When you press the button, the app plays a sound. When I set the path of the file for the sound, I use require(`./assets/${array[0].bgm}.mp3`). However, I get an error.

How can I make it work?

my app

Here is an array, where I'm going to get the name bgm for the path:

array.js

const array = [ { id: 1, name: "Ken", bgm: "bgm", }, ]; export default array; 

Here is app.js.

import * as React from "react"; import { Text, View, StyleSheet, Button } from "react-native"; import { Audio } from "expo-av"; import SoundPlayer from "./SoundPlayer"; export default function App() { return ( <View style={styles.container}> <SoundPlayer /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "center", backgroundColor: "#ecf0f1", padding: 10, }, }); 

Here is another file that contains require()

import * as React from "react"; import { Button } from "react-native"; import { Audio } from "expo-av"; import array from "./array"; export default function SoundPlayer() { const [sound, setSound] = React.useState(); async function playSound() { console.log("Loading Sound"); if (sound) { console.log("Unloading Sound"); await sound.unloadAsync(); } const { sound: newSound } = await Audio.Sound.createAsync( require(`./assets/${array[0].bgm}.mp3`) // This doesn't work. //require("./assets/bgm.mp3") //This just works. ); setSound(newSound); console.log("Playing Sound"); await newSound.playAsync(); } React.useEffect(() => { return sound ? () => { console.log("Unloading Sound"); sound.unloadAsync(); } : undefined; }, [sound]); return <Button title="Play Sound" onPress={playSound} />; } 

However, this throws an error:

error: SoundPlayer.js: SoundPlayer.js:Invalid call at line 17: require("./assets/" + _array.default[0].bgm + ".mp3")

I need some help. How would you solve this problem? Thank you in advance.

7
  • yes maybe that'll work and you can try printing the whole thing ./assets/${test}.mp3, to get the desired output bcz as u said it was working when it's only string Commented Mar 12, 2023 at 13:03
  • Thanks for replying! I tried it, but I got this error... : error: SoundPlayer.js: SoundPlayer.js:Invalid call at line 20: require("./assets/" + test + ".mp3") Commented Mar 12, 2023 at 13:11
  • can you also try const tst = ./assets/${array[0]["bgm"]}.mp3, and then require(tst) Commented Mar 12, 2023 at 13:17
  • Okay I'll do try! Commented Mar 12, 2023 at 13:19
  • 2
    Does this answer your question? require() not working with variable - react native Commented Mar 12, 2023 at 13:28

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.