[英]Audio file not playing from document directory
我在文檔目錄中有一個音頻文件,它沒有播放,但沒有出現任何錯誤或崩潰。 我真的被這種情況所困擾,提到了許多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
}
}
讓我澄清一下;
有兩種播放音頻文件的標准方法:
錄制音頻,然后使用完成處理程序將其導出到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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.