AVAudioPlayer 不播放音频 Swift

AVAudioPlayer not playing audio Swift

我正在尝试播放声音以提醒我的应用程序的用户,我查看了一些资源以帮助我做到这一点:

AVAudioPlayer not playing audio in Swift(帮我解决我现在运行的问题,没用)

Creating and playing a sound in swift(我最初开始的地方)

还有这些视频:

https://www.youtube.com/watch?v=Kq7eVJ6RSp8

https://www.youtube.com/watch?v=RKfe7xzHEZk

所有这些都没有给我想要的结果(声音不播放)。

这是我的代码:

private func playFinishedSound(){
        if let pathResource = NSBundle.mainBundle().pathForResource("3000", ofType: "mp3"){
            let finishedStepSound = NSURL(fileURLWithPath: pathResource)
            var audioPlayer = AVAudioPlayer()
            do {
                audioPlayer = try AVAudioPlayer(contentsOfURL: finishedStepSound)
                if(audioPlayer.prepareToPlay()){
                    print("preparation success")
                    audioPlayer.delegate = self
                    if(audioPlayer.play()){
                        print("Sound play success")
                    }else{
                        print("Sound file could not be played")
                    }
                }else{
                    print("preparation failure")
                }

            }catch{
                print("Sound file could not be found")
            }
        }else{
            print("path not found")
        }
    }

目前我看到 "preparation success" 和 "sound play success" 但没有播放声音。 class 我在其中实现的是一个 AVAudioPlayerDelegate,文件名为“3000.mp3”,位于项目目录中。在上下文中,该方法在此处调用:

private func finishCell(cell: TimerTableViewCell, currentTimer: TimerObject){
        currentTimer.isRunning = false
        cell.label.text = "dismiss"
        cell.backgroundColor = UIColor.lightMintColor()
        if(!currentTimer.launchedNotification){
            playFinishedSound()
        }
        currentTimer.launchedNotification = true
    }

如有任何帮助,我们将不胜感激。

UPDATE/SOLUTION:

所以问题是 audioPlayer 在播放声音之前会被释放,为了解决这个问题,我必须在 class 中将其设为 属性 而不是仅仅创建它的一个实例函数内。更新后的代码如下所示:

属性 声明中的可选引用 class:

var audioPlayer : AVAudioPlayer?

使用audioPlayer的函数:

private func playFinishedSound(){
        if let pathResource = NSBundle.mainBundle().pathForResource("3000", ofType: "mp3"){
            let finishedStepSound = NSURL(fileURLWithPath: pathResource)
            audioPlayer = AVAudioPlayer()
            do {
                audioPlayer = try AVAudioPlayer(contentsOfURL: finishedStepSound)
                if(audioPlayer!.prepareToPlay()){
                    print("preparation success")
                    audioPlayer!.delegate = self
                    if(audioPlayer!.play()){
                        print("Sound play success")
                    }else{
                        print("Sound file could not be played")
                    }
                }else{
                    print("preparation failure")
                }

            }catch{
                print("Sound file could not be found")
            }
        }else{
            print("path not found")
        }
    }