Swift检查AVAudioPlayer是否正在播放导致崩溃

6
我正在使用Swift制作音效板。它运行良好,但我正在尝试实现一个检查,即检查AVAudioPlayer实例是否正在播放,如果是,则停止它。声音在表格视图中列出,该表格获取来自数组的数据,这个数组中存储了我的Sound类(包括2个变量,声音的标题和URL)。
我在ViewController Class中拥有AVAudioPlayer、AVAudioSession以及我的声音数组。
 var session = AVAudioSession.sharedInstance()
 var audioPlayer = AVAudioPlayer()
 var sounds: [Sound] = []

当应用程序用户选择一行时,我实现了音频播放,如下所示:

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)"。您有任何想法发生了什么?或者我完全错误地执行了操作吗?预先感谢您。
1个回答

5
我已经理解了,所以我与社区分享:
我还必须在我的ViewController类上声明声音NSURL属性:
var session = AVAudioSession.sharedInstance()
var audioPlayer = AVAudioPlayer()
var audioNSURL = NSURL()

同时,在ViewDidLoad函数中准备我的音频播放器: (为了初始化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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接