简体   繁体   中英

Issue playing audio with AVAudioSession

Current code:

@IBAction func sound1(sender: UIButton)
{
    var sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Sound1", ofType: "wav")!)

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
    } catch _ {
    }
    do {
        try AVAudioSession.sharedInstance().setActive(true)
    } catch _ {
    }

    var error: NSError?
    do {
        audioPlayer = try AVAudioPlayer(contentsOfURL: sound)
    } catch var error1 as NSError {
        error = error1
        audioPlayer = nil
    }
    audioPlayer.prepareToPlay()
    audioPlayer.volume = 1
    audioPlayer.play()
}

This is the current code I had before updating this project to Swift 2.

audioPlayer = nil

The issue I get when trying to run the app is this:

Cannot assign a value of type 'NilLiteralConvertible' to a value of type 'AVAudioPlayer'

It means that your variable audioplayer is not an Optional and so can not be set to nil .

Either make it an Optional then use it with try? (note the ? ) without do catch , or do not attempt to set it to nil if you want to continue using try inside do catch .

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