Swift中AVFoundation开发:如何支持多种音频文件类型
Hey James, let's get your code sorted to support all three audio formats cleanly. Your current approach only checks for FLAC, and the structure can be simplified to handle multiple types without repeating logic. Here's how to do it right:
First, Define Your Supported Formats
Start by creating an array of all the audio types you want to support. This makes it easy to add/remove formats later without rewriting chunks of code:
let supportedAudioFormats = ["mp3", "wav", "flac"]
Scenario 1: Filtering Files from a Directory
If you're iterating through files in a directory (like your songPath loop), use the file's path extension to check if it's a supported type—this is more reliable than checking if the string contains the extension (which could false-match if a filename has .flac in it somewhere):
for song in songPath { // Get the file's extension, lowercased to handle cases like .FLAC or .MP3 guard let fileExt = song.pathExtension.lowercased() else { continue } // Check if the extension is in our supported list if supportedAudioFormats.contains(fileExt) { // Extract the filename without extension to look it up in the bundle let fileName = song.deletingPathExtension().lastPathComponent if let audioPath = Bundle.main.path(forResource: fileName, ofType: fileExt) { // Do something with your valid audio path here! print("Found valid audio file: \(audioPath)") } } }
Scenario 2: Looking Up a Specific Song (e.g., for UITableView)
If you're trying to find the path for a specific song name (like songs[indexPath.row]), loop through your supported formats to find a matching file in the bundle:
let targetSongName = songs[indexPath.row] var audioPath: String? // Check each format until we find a matching file for format in supportedAudioFormats { if let path = Bundle.main.path(forResource: targetSongName, ofType: format) { audioPath = path break // Stop searching once we find a valid path } } // Use the path if we found one if let validPath = audioPath { // Initialize your audio player or process the file here print("Using audio path: \(validPath)") } else { print("No supported audio file found for \(targetSongName)") }
Key Improvements Over Your Current Code
- Maintainable: Add new formats (like
.m4a) just by updating thesupportedAudioFormatsarray. - Accurate: Uses
pathExtensioninstead of string contains, so you won't accidentally match filenames that include the extension as part of their name (e.g.,my.flac.song.mp3). - Cleaner: Avoids repetitive
ifstatements for each format—one loop handles all types.
内容的提问来源于stack exchange,提问作者 James

