我在AppDelegate中设置了一个AVAudioPlayer,可以在启动时播放。它会继续在整个应用程序中播放,但是当我尝试停止或在其他课程中播放该播放器时,该应用程序会在该行上与EXC_BAD_ACCESS崩溃。
AppDelegate.swift
import AVFoundation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var path = NSBundle.mainBundle().pathForResource("backgroundMusic", ofType: "wav")
var soundTrack = AVAudioPlayer()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
soundTrack = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path), error: nil)
soundTrack.numberOfLoops = -1
soundTrack.volume = 0.35
soundTrack.play()
return true
}
OtherClass.swift
func aFunction() {
let appDelegate = AppDelegate()
appDelegate.soundTrack.stop() //Here is where the app crashes. Same with .play()
}
感谢您的帮助!
答案 0 :(得分:4)
通过执行AppDelegate()
您正在创建一个新的app delegate实例;一个变量尚未启动的变量。您想获得UiApplications共享委托:
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate