如何加载Swift Bundle中指定文件夹内的资源文件
Bundle 资源加载实现示例
需求说明
需要加载default-sound目录下的文件a,该文件在Bundle中的结构如下:
实现方式1:路径拼接定位
首先参照普通目录结构的使用方式,尝试用/拼接路径定位文件夹,实现代码如下:
import Foundation import AVFoundation struct TtsPronounciationError: Error { enum ErrorKind { case loadingError } let kind: ErrorKind let path: String let char: Character init(kind: ErrorKind, path: String, char: Character) { self.path = path self.kind = kind self.char = char } } struct TtsPronounciation { var char: Character var audioFile: AVAudioPlayer static func fromBundle(char: Character, bundleFileName: String) throws -> TtsPronounciation { Bundle.main.load() if let path = Bundle.main.path(forResource: bundleFileName, ofType: nil) { let url = URL(fileURLWithPath: path) do { let sound = try AVAudioPlayer(contentsOf: url) return self.init(char: char, audioFile: sound) } catch let e { print(#function, "error", e) throw TtsPronounciationError(kind: .loadingError, path: bundleFileName, char: char) } } else { print(#function, " - error", "could not find \(bundleFileName)") throw TtsPronounciationError(kind: .loadingError, path: bundleFileName, char: char) } } } do { var a = try TtsPronounciation.fromBundle(char: "a", bundleFileName: "default-sound/a") } catch { print("could not find the file in bundle") }
实现方式2:inDirectory参数定位
之后尝试使用Bundle.main.path方法的inDirectory参数定位Bundle目录中存储的文件,实现代码如下:
import Foundation import AVFoundation struct TtsPronounciationError: Error { enum ErrorKind { case loadingError } let kind: ErrorKind let path: String let char: Character init(kind: ErrorKind, path: String, char: Character) { self.path = path self.kind = kind self.char = char } } struct TtsPronounciation { var char: Character var audioFile: AVAudioPlayer static func fromBundle(char: Character, bundleFileName: String, inDirectory: String?) throws -> TtsPronounciation { Bundle.main.load() if let path = inDirectory != nil ? Bundle.main.path(forResource: bundleFileName, ofType: nil, inDirectory: inDirectory) : Bundle.main.path(forResource: bundleFileName, ofType: nil) { let url = URL(fileURLWithPath: path) do { let sound = try AVAudioPlayer(contentsOf: url) return self.init(char: char, audioFile: sound) } catch let e { print(#function, "error", e) throw TtsPronounciationError(kind: .loadingError, path: bundleFileName, char: char) } } else { print(#function, " - error", "could not find \(bundleFileName)") throw TtsPronounciationError(kind: .loadingError, path: bundleFileName, char: char) } } } do { var a = try TtsPronounciation.fromBundle(char: "a", bundleFileName: "a", inDirectory: "default-sound") } catch { print("could not locate the sound") }
内容的提问来源于stack exchange,提问作者The epic face 007
相关产品推荐
相关产品推荐

