0
votes

I am using the AVAudioPlayer Framework and I choose to play a song when I enter a region (I am using the Core Location framework and call this function when I use the didEnterRegion function).

...
var audioPlayer = AudioPlayer()
...
func playMusic(regionIdentifier: String!){
    //Get Documents Directory
    let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
    //Get region label with music file
    var musicFile = db.selectRegion(regionIdentifier)
    //If music file exists, play specified music file.
    if(musicFile != ""){
        var error:NSError?
        var musicFilePath = documentsDirectory + "/" + musicFile
        audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: musicFilePath), error:&error)
        audioPlayer.prepareToPlay()
        audioPlayer.play()
    }
    else{
        NSLog("File is not in Database.")
    }
}

The first time I enter a region, the audio player plays the music clip fine. However, it seems like when I want to replay a song I have already played before (I am visiting a region I have already visited before), my song does not replay. I know that the function didEnterRegion is called correctly and I tried to find if I had an error in the AVAudioPlayer when playing the song a second time but that didn't seem to produce any error. Any ideas as to why my song won't play a second time? Thanks! I've also looked at AVAudioPlayer won't play existing file a second time and have tried to turn the NSURL to a type NSData but I still received the same results.

EDIT: I have even tried to print out if the play() function returns true and it does indeed return true.

2

2 Answers

0
votes

Try reseting the audioplayer, before playing it:

audioPlayer.stop()
audioPlayer.currentTime = 0
audioPlayer.play()
0
votes

Create 2 functions, the first one for loading the sound file in the audioPlayer and the second one for playing sound:

var audioPlayer = AVAudioPlayer()!

func LoadSoundFile(regionIdentifier: String!){
//Get Documents Directory
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
//Get region label with music file
var musicFile = db.selectRegion(regionIdentifier)
//If music file exists, play specified music file.
if(musicFile != ""){
    var error:NSError?
    var musicFilePath = documentsDirectory + "/" + musicFile
    audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: musicFilePath), error:&error)
}
else{
    NSLog("File is not in Database.")
}
}

In the playSound function write this:

func playSound(){
  audioPlayer.stop()
  audioPlayer.prepareToPlay()    // Not necessary
  audioPlayer.play()
}

The playSound function can be invoked by an action (button pressed)