I figured this out, so I am communicating with the community:
I also had to declare an NSURL sound property in my ViewController class :
var session = AVAudioSession.sharedInstance() var audioPlayer = AVAudioPlayer() var audioNSURL = NSURL()
and also prepare my audio player for the ViewDidLoad function: (I had to use a sound sample to initialize AVAudioPlayer)
let samplePath = NSBundle.mainBundle().pathForResource("sample", ofType: "mp4") audioNSURL = NSURL.fileURLWithPath(samplePath!)! audioPlayer = AVAudioPlayer(contentsOfURL: audioNSURL, error: nil) audioPlayer.prepareToPlay()
then, in the didSelectRowAtIndexPath method, I check to see if an instance of AVAudioPlayer is playing, and also if it is playing sound reflected from the selected cell. If yes, stop the audio player, if not, then play another sound (the audio player stops and plays another sound)
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var sound = self.sounds[indexPath.row] var baseString : String = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as String var pathComponents = [baseString, sound.url] var rowSoundURL = NSURL.fileURLWithPathComponents(pathComponents)! if audioPlayer.playing && rowSoundURL == audioNSURL { audioPlayer.stop() } else { audioNSURL = rowSoundURL self.audioPlayer = AVAudioPlayer(contentsOfURL: audioNSURL, error: nil) self.audioPlayer.play() } tableView.deselectRowAtIndexPath(indexPath, animated: true) }
Remember that if you also record sounds in your application, you must set the session category as AVAUdioSessionCategoryPlayback or the sound will be heard through the small speaker of the device. So, in the viewWillAppear function:
session.setCategory(AVAudioSessionCategoryPlayback, error: nil)