創(chuàng)建一個類用來播放音樂,命名為AudioHelper簸州,具體swift代碼如下:
import UIKit
import AVFoundation
class AudioHelper: NSObject {
//第一種方式,簡單的音頻播放
func playSound(audioUrl: NSURL, isAlert: Bool , playFinish: ()->()) {
// 一. 獲取 SystemSoundID
// 參數(shù)1: 文件路徑
// 參數(shù)2: SystemSoundID, 指針
let urlCF = audioUrl as CFURLRef
var systemSoundID: SystemSoundID = 0
AudioServicesCreateSystemSoundID(urlCF, &systemSoundID)
// AudioServicesDisposeSystemSoundID(systemSoundID)
// 二. 開始播放
if isAlert {
// 3. 帶振動播放, 可以監(jiān)聽播放完成(模擬器不行)
AudioServicesPlayAlertSound(systemSoundID)
}else {
// 3. 不帶振動播放, 可以監(jiān)聽播放完成
AudioServicesPlaySystemSound(systemSoundID)
}
playFinish()
}
//第二種使用AVAudioPlayer播放
// 獲取音頻會話
let session = AVAudioSession.sharedInstance()
var player: AVAudioPlayer?
var currentURL : NSURL?
let playFinish = "playFinsh"
override init() {
super.init()
do{
// 設(shè)置會話類別
try session.setCategory(AVAudioSessionCategoryPlayback)
// 激活會話
try session.setActive(true)
}catch {
print(error)
return
}
}
//paly music
func playMusic(filePath: String) {
guard let url = NSURL(string: filePath) else {
return//url不存在
}
do{
//AVAudioSessionCategoryPlayback揚聲器模式
try session.setCategory(AVAudioSessionCategoryPlayback)
}catch {
print(error)
return
}
//如果播放的音樂與之前的一樣牡整,則繼續(xù)播放
if currentURL == url {
player?.play()
return
}
do {
player = try AVAudioPlayer(data: NSFileManager.defaultManager().contentsAtPath(filePath)!)
currentURL = url
player?.delegate = self
//開啟紅外感知功能
// UIDevice.currentDevice().proximityMonitoringEnabled = true
// NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(proxumityStateChange), name: "UIDeviceProximityStateDidChangeNotification", object: nil)
player?.prepareToPlay()
player?.play()
print("播放成功榜轿,文件路徑 ==\(url)")
}catch {
print(error)
return
}
}
//配合紅外感知功能
// func proxumityStateChange(notification:NSNotification){
// if UIDevice.currentDevice().proximityState == true{
// //使用聽筒模式,屏幕變暗
// do{
// try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
// }catch {
// print(error)
// return
// }
// }else{
// //使用揚聲器模式
// do{
// try session.setCategory(AVAudioSessionCategoryPlayback)
// }catch {
// print(error)
// return
// }
// }
// }
// 暫停當(dāng)前歌曲/pause current music
func pauseCurrentMusic() -> () {
player?.pause()
}
// 繼續(xù)播放當(dāng)前歌曲/continue to play current music
func resumeCurrentMusic() -> () {
player?.play()
}
// 播放到指定時間/play music to specified time
func seekToTime(time: NSTimeInterval) -> () {
player?.currentTime = time
}
class func getFormatTime(timeInterval: NSTimeInterval) -> String {
let min = Int(timeInterval) / 60
let sec = Int(timeInterval) % 60
let timeStr = String(format: "%02d:%02d", min, sec)
return timeStr
}
class func getTimeInterval(formatTime: String) -> NSTimeInterval {
// 00:00.89 == formatTime
let minSec = formatTime.componentsSeparatedByString(":")
if minSec.count == 2 {
let min = NSTimeInterval(minSec[0]) ?? 0
let sec = NSTimeInterval(minSec[1]) ?? 0
return min * 60 + sec
}
return 0
}
}
extension AudioHelper: AVAudioPlayerDelegate {
//播放完成后的回調(diào)
func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
print("播放完成")
NSNotificationCenter.defaultCenter().postNotificationName(playFinish, object: nil)
self.currentURL = nil
}
}
然后外界調(diào)用的話是這樣的:
self.audioPlayer = AudioHelper()
self.audioPlayer.playMusic(filePath)