我試圖在更改爲另一個視圖時讓背景音樂停止播放。Swift:如何在更改視圖時停止背景音樂
我有一個全局變量來播放音樂
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()
}
添加MusicHelper.sharedHelper.stopBackgroundMusic()到viewWillDisappear()例如有什麼問題? – Gruntcakes