如何修改Expo-AV录制文件(FileSystem)的文件名?
Got it, let's get your recording filenames changed from the default recording-*.3gp to NameOfApp-*.3gp — it's straightforward once you know how to specify a custom output URI with expo-av!
Here's what you need to do:
The default filename comes from expo-av automatically generating a URI when you don't specify one. To override this, you'll construct a custom file URI using expo-file-system to get a valid storage path, plus a unique identifier to avoid overwriting files.
Step 1: Install required dependencies (if missing)
You'll need expo-file-system (for directory access) and optionally expo-crypto (to generate a reliable unique ID):
npx expo install expo-file-system expo-crypto
Step 2: Build your custom file URI
In your recording logic, create a URI that uses your app name plus a unique ID. Here's a code snippet:
import { Audio } from 'expo-av'; import * as FileSystem from 'expo-file-system'; import * as Crypto from 'expo-crypto'; // Function to create a custom recording URI async function getCustomRecordingURI() { // Get the app's document directory (where recordings are stored by default) const documentDir = FileSystem.documentDirectory; // Generate a unique UUID to avoid duplicate filenames const uuid = await Crypto.randomUUID(); // Replace "YourAppName" with your actual app name return `${documentDir}YourAppName-${uuid}.3gp`; }
Step 3: Use the custom URI when starting a recording
When you initialize your recording, pass the custom URI to Audio.Recording.createAsync():
async function startRecording() { try { // Request recording permission (you probably already have this) const permission = await Audio.requestPermissionsAsync(); if (!permission.granted) return; // Initialize audio mode await Audio.setAudioModeAsync({ allowsRecordingIOS: true, playsInSilentModeIOS: true, }); // Get your custom URI const recordingURI = await getCustomRecordingURI(); // Create the recording with your custom URI const { recording } = await Audio.Recording.createAsync( Audio.RecordingOptionsPresets.HIGH_QUALITY, recordingURI // This is the key line to override the default filename ); // Store the recording instance for later use (playback, stopping, etc.) this.recording = recording; console.log('Recording started with URI:', recordingURI); } catch (err) { console.error('Failed to start recording:', err); } }
Key Notes:
- File Format: We're keeping the
.3gpextension since that's what you're using now — expo-av supports this format by default, so no changes needed there. - Unique IDs: Using
Crypto.randomUUID()ensures each filename is unique, preventing accidental overwrites of old recordings. - Storage Location:
FileSystem.documentDirectoryis the default location expo-av uses, so your recordings will still be stored in the same place, just with the new filename.
That's it! Now every recording you make will have the format YourAppName-<unique-id>.3gp instead of the default.
内容的提问来源于stack exchange,提问作者Drioueche Mohammed

