Swift AVAudioPlayer wont play audio recorded with AVAudioRecorder

浪尽此生 提交于 2019-12-19 12:48:13

问题


I have built an app that records an audio clip, and saves it to a file called xxx.m4a.

Once the recording is made, I can find this xxx.m4a file on my system and play it back - and it plays back fine. The problem isn't recording this audio track.

My problem is playing this audio track back from within the app.

// 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)")
}

My console output when I run this code is like this:

audio file exists!
about to play
told to play

I dont get anything logged into the console from either audioPlayerDidFinishPlaying or audioPlayerDecodeErrorDidOccur.

Can someone explain to me why I my audio clip isnt playing?

Many thanks.


回答1:


You playing code is fine; your only problem is with the scope of your AVAudioPlayer object. Basically, you need to keep a strong reference to the player around all the time it's playing, otherwise it'll be destroyed by ARC, as it'll think you don't need it any more.

Normally you'd make the AVAudioPlayer object a property of whatever class your code is in, rather than making it a local variable in a method.




回答2:


In the place where you want to use the Playback using speakers before you initialize your AVAudioPlayer, add the following code:

let recordingSession = AVAudioSession.sharedInstance()
        do{
            try recordingSession.setCategory(AVAudioSessionCategoryPlayback)
        }catch{

        }

and when you are just recording using AVAudioRecorder use this before initializing that:

do {
            recordingSession = AVAudioSession.sharedInstance()
            try recordingSession.setCategory(AVAudioSessionCategoryRecord)
    }catch {}


来源:https://stackoverflow.com/questions/27423243/swift-avaudioplayer-wont-play-audio-recorded-with-avaudiorecorder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!