[英]AVPlayer does not play file recorded with AVAudioRecorder — Swift
[英]Swift AVAudioPlayer wont play audio recorded with AVAudioRecorder
我已經構建了一個記錄音頻剪輯的應用程序,並將其保存到名為xxx.m4a
的文件中。
錄制完成后,我可以在系統上找到此xxx.m4a
文件並進行播放-可以正常播放。 問題不在於錄制此音軌。
我的問題是從應用程序中播放此音頻軌道。
// to demonstrate how I am building the recordedFileURL
let currentFileName = "xxx.m4a"
let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let docsDir: AnyObject = dirPaths[0]
let recordedFilePath = docsDir.stringByAppendingPathComponent(currentFileName)
var recordedFileURL = NSURL(fileURLWithPath: recordedFilePath)
// quick check for my own sanity
var checkIfExists = NSFileManager.defaultManager()
if checkIfExists.fileExistsAtPath(recordedFilePath){
println("audio file exists!")
}else{
println("audio file does not exist")
}
// play the recorded audio
var error: NSError?
let player = AVAudioPlayer(contentOfURL: recordedFileURL!, error: &error)
if player == nil {
println("error creating avaudioplayer")
if let e = error {
println(e.localizedDescription)
}
}
println("about to play")
player.delegate = self
player.prepareToPlay()
player.volume = 1.0
player.play()
println("told to play")
// -------
// further on in this class I have the following delegate methods:
func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool){
println("finished playing (successfully? \(flag))")
}
func audioPlayerDecodeErrorDidOccur(player: AVAudioPlayer!, error: NSError!){
println("audioPlayerDecodeErrorDidOccur: \(error.localizedDescription)")
}
運行此代碼時,控制台輸出如下:
audio file exists!
about to play
told to play
我沒有從audioPlayerDidFinishPlaying
或audioPlayerDecodeErrorDidOccur
將任何內容登錄到控制台。
有人可以向我解釋為什么我的音頻片段無法播放嗎?
非常感謝。
您玩代碼很好; 您唯一的問題是AVAudioPlayer
對象的范圍。 基本上,您需要在播放器的所有時間內始終保持對播放器的強烈引用,否則它將被ARC銷毀,因為它認為您不再需要它。
通常,您將使AVAudioPlayer對象成為代碼所在類的屬性,而不是使它成為方法中的局部變量。
在初始化AVAudioPlayer之前要使用揚聲器播放的地方,添加以下代碼:
let recordingSession = AVAudioSession.sharedInstance()
do{
try recordingSession.setCategory(AVAudioSessionCategoryPlayback)
}catch{
}
當您僅使用AVAudioRecorder進行錄制時,請在初始化之前使用以下代碼:
do {
recordingSession = AVAudioSession.sharedInstance()
try recordingSession.setCategory(AVAudioSessionCategoryRecord)
}catch {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.