React Native中能否通过绝对路径播放音频?react-native-audio-android场景咨询
Hey there! Let's break down your two React Native audio-related questions clearly, with practical code examples to help you out.
Absolutely yes! Most popular React Native audio libraries support loading and playing audio files using absolute file paths. The key is to use a reliable library that handles local file system access properly.
A common choice is react-native-sound (it works seamlessly for both iOS and Android). Here's a quick, actionable example:
First, install the library:
npm install react-native-sound --save # Or for yarn users: yarn add react-native-sound
Then, implement the playback logic in your component:
import Sound from 'react-native-sound'; // Function to play audio from an absolute path const playAudioFromPath = (audioAbsolutePath) => { try { // For Android, set the audio category first to ensure proper playback Sound.setCategory('Playback'); const soundInstance = new Sound(audioAbsolutePath, '', (loadError) => { if (loadError) { console.log('Failed to load audio file:', loadError); return; } // Start playback soundInstance.play((playSuccess) => { if (!playSuccess) { console.log('Playback failed unexpectedly'); } // Release the audio resource once playback finishes to avoid memory leaks soundInstance.release(); }); }); } catch (err) { console.error('Error during playback:', err); } }; // Call the function with your target absolute path playAudioFromPath('/storage/emulated/0/AUDIO_:20180403_151649.3gp');
Important note: Make sure your app has the necessary file system permissions. For Android, add READ_EXTERNAL_STORAGE (or READ_MEDIA_AUDIO for Android 13+) to your AndroidManifest.xml. For iOS, adjust Info.plist permissions if needed.
Since you already get the absolute path of the recorded audio from react-native-audio-android, you can reuse the playback approach above to preview the audio before uploading. Here's a complete integrated example:
Step 1: Verify permissions
Add these to your android/app/src/main/AndroidManifest.xml for recording and file access:
<uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <!-- For Android 13+, replace READ/WRITE with: --> <!-- <uses-permission android:name="android.permission.READ_MEDIA_AUDIO" /> -->
Step 2: Full component with recording + playback
import React, { useState } from 'react'; import { View, Button, Text, StyleSheet } from 'react-native'; import Sound from 'react-native-sound'; import AudioAndroid from 'react-native-audio-android'; const AudioRecorderPreview = () => { const [recordedPath, setRecordedPath] = useState(null); // Start recording const startRecording = async () => { try { await AudioAndroid.startRecording(); console.log('Recording started'); } catch (err) { console.error('Failed to start recording:', err); } }; // Stop recording and save the path const stopRecording = async () => { try { const path = await AudioAndroid.stopRecording(); setRecordedPath(path); console.log('Recording stopped. File path:', path); } catch (err) { console.error('Failed to stop recording:', err); } }; // Play the recorded audio const playRecordedAudio = () => { if (!recordedPath) { console.log('No recorded audio to play!'); return; } Sound.setCategory('Playback'); const sound = new Sound(recordedPath, '', (loadError) => { if (loadError) { console.log('Failed to load recorded audio:', loadError); return; } sound.play((playSuccess) => { if (!playSuccess) { console.log('Playback failed'); } sound.release(); }); }); }; return ( <View style={styles.container}> <Button title="Start Recording" onPress={startRecording} /> <Button title="Stop Recording" onPress={stopRecording} style={styles.buttonMargin} /> {recordedPath && ( <Button title="Preview Recorded Audio" onPress={playRecordedAudio} style={styles.buttonMargin} /> )} {recordedPath && ( <Text style={styles.pathText}>Recorded file path: {recordedPath}</Text> )} </View> ); }; const styles = StyleSheet.create({ container: { padding: 20, justifyContent: 'center', }, buttonMargin: { marginTop: 10, }, pathText: { marginTop: 15, fontSize: 12, color: '#666', }, }); export default AudioRecorderPreview;
Quick tips for robustness:
- Always handle errors (file loading failures, playback issues) to avoid app crashes.
- Release the sound resource with
sound.release()after playback to prevent memory leaks. - For iOS, add
NSMicrophoneUsageDescriptiontoInfo.plistto request recording permissions.
内容的提问来源于stack exchange,提问作者renren

