React Native 播放 MP3 文件并自动循环播放下一首 - 代码示例
{"title":"React Native 播放 MP3 文件并自动循环播放下一首 - 代码示例", "description":"本代码示例展示了如何在 React Native 中点击按钮播放 MP3 文件,并在播放完毕后延迟 2 秒自动播放下一首。代码包含了使用 react-native-sound 库和音频文件管理。", "keywords":"React Native, MP3 播放, 音频播放, react-native-sound, 自动播放, 循环播放, 代码示例", "content":"import React, { useState, useEffect } from 'react';\nimport { View, Button } from 'react-native';\nimport Sound from 'react-native-sound';\n\nconst audioFiles = [\n require('./audio/file1.mp3'),\n require('./audio/file2.mp3'),\n require('./audio/file3.mp3')\n];\n\nconst App = () => {\n const [currentIndex, setCurrentIndex] = useState(0);\n\n const playAudio = () => {\n const sound = new Sound(audioFiles[currentIndex], Sound.MAIN_BUNDLE, (error) => {\n if (error) {\n console.log('Error loading sound', error);\n return;\n }\n\n sound.play((success) => {\n if (success) {\n console.log('Sound played successfully');\n setTimeout(() => {\n if (currentIndex < audioFiles.length - 1) {\n setCurrentIndex(currentIndex + 1);\n } else {\n setCurrentIndex(0);\n }\n }, 2000);\n } else {\n console.log('Sound playback failed');\n }\n });\n });\n };\n\n useEffect(() => {\n Sound.setCategory('Playback');\n }, []);\n\n return (\n <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>\n \n \n );\n};\n\nexport default App;\n"}
原文地址: https://www.cveoy.top/t/topic/o74I 著作权归作者所有。请勿转载和采集!