1.简单使用
import UIKit import AVFoundation class ViewController: UIViewController { lazy var player: AVAudioPlayer? = { // 1. 创建播放器(NSURL, 只能是本地URL 地址, 远程音乐, 使用这个类, 播放不了) let url = Bundle.main.url(forResource: "简单爱.mp3", withExtension: nil) do { let player = try AVAudioPlayer(contentsOf: url!) player.delegate = self // 设置可以速率播放 player.enableRate = true // 准备播放 player.prepareToPlay() // 开始播放 //player.play() return player }catch { print(error) return nil } }() func playBack() -> () { // 1. 获取音频会话 let audioSession: AVAudioSession = AVAudioSession.sharedInstance() do { // 2. 设置会话类型 if #available(iOS 10.0, *) { try audioSession.setCategory(.playback, mode: .default, options: .defaultToSpeaker) } else { // Fallback on earlier versions } // 3. 激活会话 try audioSession.setActive(true) }catch { print(error) } } @IBAction func play() { playBack() player?.play() } @IBAction func pause() { player?.pause() } @IBAction func stop() { // 重置当前播放事件 player?.currentTime = 0 player?.stop() } @IBAction func kuaijin() { // 这个值, 自动会做好容错适配, 不需要我们处理, 负数, 或者, 大于最大播放时长的数值 player?.currentTime += 15 } @IBAction func kuaitui() { player?.currentTime -= 15 } @IBAction func ratePlay() { player?.rate = 10.0 } @IBAction func volumn(sender: UISlider) { player?.volume = sender.value } } extension ViewController: AVAudioPlayerDelegate { func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { print("播放完成") } }
请发表评论