简体   繁体   中英

Stopping or Playing AVAudioPlayer From Another Class - App Crashes - Swift

I have an AVAudioPlayer set up in my AppDelegate to play on startup. It continues playing throughout the app, but when I try to stop or play the player in a different class, the app crashes with EXC_BAD_ACCESS on that line.

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

Thanks for any help!

by doing AppDelegate() you are creating a new instance of app delegate; one which the variables haven't been initiated. You want to get the UiApplications shared delegate:

let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM