简体   繁体   中英

Playing audio file in Swift using AVPlayer

I have a very simple method for playing an mp3 audio file in Swift using AVPlayer .

The problem is, it seems too simple. For example, in cases where there is an issue with the playback, an issue with the file, an issue with the device audio, how can the playback fail gracefully instead of the app crashing?

Or is the below playback code safe?

import UIKit

import AVFoundation

var audioPlayer:AVPlayer!

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        audioPlayer = AVPlayer(URL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("myResourceFileName", ofType: "mp3")!))
        audioPlayer.play()

    }

}

Why don't you try "Do" and "Catch"?

do {let path = NSBundle.mainBundle().pathForResource("myResourceFileName", ofType: "mp3")
     let soundUrl = NSURL(fileURLWithPath: path!)
     try audioPlayer = AVAudioPlayer(contentsOfURL: soundUrl)
         audioPlayer.prepareToPlay()            
   } catch let err as NSError {
       print(err.debugDescription)
   }

and place audioPlayer.play() at a function where you want to play.

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