Swift中AVFoundation的简单使用
AVAudioPlayer的简单使用
import AVFoundation class ViewController: UIViewController,AVAudioPlayerDelegate{ var audioPlayer:AVAudioPlayer? //AVAudioPlayerDelegate public func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool){ print("播放完成") } override func viewDidLoad() { super.viewDidLoad() DispatchQueue.global().async {[weak self]in let mainBoundle = Bundle.main let filePath = mainBoundle.path(forResource: "music", ofType: "mp3") if let path = filePath{ let fileData = NSData.init(contentsOfFile: path) do{ try self!.audioPlayer = AVAudioPlayer.init(data: fileData! as Data) self!.audioPlayer?.delegate = self; if self!.audioPlayer!.prepareToPlay() && self!.audioPlayer!.play(){ print("success") }else{ print("error") } }catch{ print("catch:error") } } } } }