我在文档目录中有一个音频文件,它没有播放,但我没有收到任何错误或崩溃。我真的被这种情况困住了,引用了很多 SO 链接,但没有一个能解决我的问题。
var myPlayer = AVAudioPlayer()
let fileManager = NSFileManager.defaultManager()
let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
if let documentDirectoryURL: NSURL = urls.first {
print(documentDirectoryURL)// File copied to this directory
let soundURL = documentDirectoryURL.URLByAppendingPathComponent("09.mp3")
do {
myPlayer = try AVAudioPlayer(contentsOfURL: soundURL)
myPlayer.delegate = self
myPlayer.prepareToPlay()
myPlayer.play()
} catch let error as NSError {
NSLog("Unresolved error \(error.debugDescription)")
// SHOW ALERT OR SOMETHING
}
}
Best Answer-推荐答案 strong>
让我澄清一下;
播放音频文件有两种标准方式:
录制音频,然后使用完成处理程序将其导出到应用程序(文档目录)内的文件中。从那里我们可以从文档目录访问该文件。
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 12000.0,
AVNumberOfChannelsKey: 1 as NSNumber,
AVEncoderAudioQualityKey: AVAudioQuality.High.rawValue
]
do {
audioURL = let audioFilename = getDocumentsDirectory().stringByAppendingPathComponent("recording.m4a")
let audioURL = NSURL(fileURLWithPath: audioFilename)
audioRecorder = try AVAudioRecorder(URL: audioURL, settings: settings)
}
class func getDocumentsDirectory() -> String {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0]
return documentsDirectory
}
还有更多你喜欢的实际录音等等。这里有一个教程
https://www.hackingwithswift.com/example-code/media/how-to-record-audio-using-avaudiorecorder
--或--
我们在计算机上有一个音频,您将其传输到 XCode,您可以使用它调用它
myPlayer = try AVAudioPlayer(fileURLWithPath: "09.mp3")
关于ios - 音频文件未从文档目录播放,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/38030199/
|