Swift AVAudioPlayer wont play audio recorded with

2019-03-05 03:04发布

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.

2条回答
等我变得足够好
2楼-- · 2019-03-05 03:21

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 {}
查看更多
Lonely孤独者°
3楼-- · 2019-03-05 03:27

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.

查看更多
登录 后发表回答