AVAudioPlayer没有播放音频Swift

时间:2016-08-04 15:15:33

标签: ios swift avaudioplayer

我正在尝试播放声音,向我的应用用户发出警告,并且我试图帮助我这样做了几个来源:

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")
        }
    }

目前我看到"准备成功"并且"声音播放成功"但没有播放声音。我实现它的类是一个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
    }

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:10)

更新/解决方案:

所以问题是audioPlayer在播放声音之前会被解除分配,为了解决这个问题,我必须让它成为类中的属性而不是仅仅在函数中创建它的实例。更新后的代码如下所示:

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

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")
        }
    }