Swift:如何在更改视图时停止背景音乐

时间:2016-12-06 21:24:49

标签: ios swift avaudioplayer

当我换到另一个视图时,我正试图让背景音乐停止播放。

我有一个播放音乐的全局变量

import Foundation
import AVFoundation

class MusicHelper {
    static let sharedHelper = MusicHelper()
    var audioPlayer: AVAudioPlayer?

    func playBackgroundMusic() {
        let aSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "The Walking Dead", ofType: "mp3")!)
        do {
            audioPlayer = try AVAudioPlayer(contentsOf:aSound as URL)
            audioPlayer!.numberOfLoops = -1
            audioPlayer!.prepareToPlay()
            audioPlayer!.play()
        } catch {
            print("Cannot play the file")
        }
    }
}

然后我将音乐加载到视图中

import UIKit
import SwiftGifOrigin
import AVFoundation

class ViewController: UIViewController {
    var audioPlayer: AVAudioPlayer?

    @IBOutlet weak var introGif: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Gif intro
        self.introGif.image = UIImage.gifWithName("WalkingDeadIntro")

        _ = try! Data(contentsOf: Bundle.main.url(forResource: "WalkingDeadIntro", withExtension: "gif")!)
        //self.bottomImageView.image = UIImage.gif(data: imageData)

        // Load background Music
        MusicHelper.sharedHelper.playBackgroundMusic()
    }

1 个答案:

答案 0 :(得分:0)

只要写下面的代码就可以在视图发生变化时停止播放器,前提是audioPlayer是你提到的全局变量。

override func viewWillDisappear( ) {
audioPlayer.stop( )
}