我正在用Swift制作音板。它工作得很好,但我试图检查AVAudioPlayer实例是否正在播放,如果是,则停止它。声音列在tableview上,它从我存储Sound类的数组中获取数据(其中包含2个变量,标题和声音url)。
我的AVAudioPlayer和AVAudioSession以及我的ViewController类上的声音数组:
var session = AVAudioSession.sharedInstance()
var audioPlayer = AVAudioPlayer()
var sounds: [Sound] = []
当app用户选择这样的行时,我实现音频播放:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if audioPlayer.playing {
audioPlayer.stop()
} else {
var sound = self.sounds[indexPath.row]
var baseString : String = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as String
var pathComponents = [baseString, sound.url]
var audioNSURL = NSURL.fileURLWithPathComponents(pathComponents)
self.audioPlayer = AVAudioPlayer(contentsOfURL: audioNSURL, error: nil)
self.audioPlayer.play()
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
但是当我点击该行时,应用程序崩溃了,我得到的只是“(lldb)”
你知道发生了什么吗?或者我完全错了吗?
提前谢谢
答案 0 :(得分:5)
我明白了,所以我与社区分享:
我还必须在 ViewController类上声明声音NSURL属性:
var session = AVAudioSession.sharedInstance()
var audioPlayer = AVAudioPlayer()
var audioNSURL = NSURL()
还要在 ViewDidLoad 功能上准备我的audioPlayer: (我必须使用示例声音来初始化AVAudioPlayer)
let samplePath = NSBundle.mainBundle().pathForResource("sample", ofType: "mp4")
audioNSURL = NSURL.fileURLWithPath(samplePath!)!
audioPlayer = AVAudioPlayer(contentsOfURL: audioNSURL, error: nil)
audioPlayer.prepareToPlay()
然后,在didSelectRowAtIndexPath方法中,我检查AVAudioPlayer实例是否正在播放,以及它是否正在播放被轻击的单元格反射的声音。如果是,请停止audioPlayer,如果没有,则播放其他声音(audioPlayer停止并播放其他声音)
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)
}
请注意,如果您还在应用上录制声音,则必须将会话类别设置为AVAUdioSessionCategoryPlayback,否则将通过设备的小型扬声器听到声音。所以,在viewWillAppear函数中:
session.setCategory(AVAudioSessionCategoryPlayback, error: nil)