我有一个位于文档目录中的音频文件,但它没有播放,但我没有收到任何错误或崩溃。我真的坚持这种情况,提到了许多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
}
}
答案 0 :(得分:0)
让我澄清一下;
播放音频文件有两种标准方法:
录制音频,然后使用完成处理程序将其导出到App(文档目录)内的文件中。从那里我们可以从文档目录访问该文件。
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")