viewWillDisappear错误/当我更改viewController时停止播放声音

时间:2017-12-24 15:33:23

标签: ios swift audio

我有一些ViewCotroller,我点按了一个按钮 - 正在播放一些音频文件。我想在更改/关闭此ViewController时停止播放音频。我怎么能这样做?

我尝试为viewWillDisappear添加一些方法,如果我没有点击任何按钮就会崩溃。但是,如果我点击一些按钮 - 它将正常工作。

import UIKit
import AVFoundation

class BossViewController: UIViewController {

    var audioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    //MARK: - Stop sound when we're change/close this viewController

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        audioPlayer.stop()
    } 

这就是我的按钮的样子:

@IBAction func boss1(_ sender: AnyObject) {

        let audioFile = NSURL(fileURLWithPath: Bundle.main.path(forResource: "shamp", ofType: "mp3")!)
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: audioFile as URL)
            audioPlayer.prepareToPlay()
        } catch {
            print("Problem in getting File")
        }

        audioPlayer.play()
    }

1 个答案:

答案 0 :(得分:0)

您可以检查音频播放器是否正在播放,如@SandeepBhandari所述,或者您可以使用Bool变量来跟踪用户是否点按了按钮:

var buttonTapped = false

@IBAction func boss1(_ sender: AnyObject) {
    ...
    buttonTapped = true
}

然后,您可以使用viewWillDisappear(_ animated: Bool)方法检查变量:

override func viewWillDisappear(_ animated: Bool) {
    if buttonTapped {
        audioPlayer.stop()
    }
}