AVAudioPlayer
The AVAudioPlayer class lets you play sound in any audio format available in iOS and macOS.
AVAudioPlayer可以播放任何iOS和macOS支持的音頻格式(.mp3括勺、.caf、.aac)的本地音頻文件
do{
let audioPlayer = try AVAudioPlayer.init(contentsOf: audioUrl)
audioPlayer.rate = 1.5 //播放速率
audioPlayer.numberOfLoops = 0//循環(huán)播放次數(shù)
audioPlayer.volume = 0.8//音量
audioPlayer.pan = 0.0 //切換聲道 -1.0左聲道 0 雙聲道 1.0 右聲道
audioPlayer.delegate = self//
audioPlayer.play()
}catch{
}
AVAudioPlayerDelegate
//播放結(jié)束
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
}
//解碼失敗
func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
print("解碼失敗")
}
//中斷開始
func audioPlayerBeginInterruption(_ player: AVAudioPlayer) {
}
//中斷結(jié)束
func audioPlayerEndInterruption(_ player: AVAudioPlayer, withOptions flags: Int) {
}
通知處理中斷
NotificationCenter.default.addObserver(self, selector: #selector(handleAudioInterrupution), name: NSNotification.Name.AVAudioSessionInterruption, object: AVAudioSession.sharedInstance())
@objc func handleAudioInterrupution(notification:NSNotification ){
let userInfo = notification.userInfo
guard userInfo != nil else {
return
}
if let ininterruptionType = userInfo![AVAudioSessionInterruptionTypeKey] as? AVAudioSessionInterruptionType{
if ininterruptionType == AVAudioSessionInterruptionType.began{
print("AVAudioSessionInterruptionType.began")
}else{
if let options = userInfo![AVAudioSessionInterruptionOptionKey] as? AVAudioSessionInterruptionOptions, options == AVAudioSessionInterruptionOptions.shouldResume{
print("AVAudioSessionInterruptionType.end let's resume")
}
}
}
}
通知處理音道變化
NotificationCenter.default.addObserver(self, selector: #selector(handleAudioSessionRouteChange), name: NSNotification.Name.AVAudioSessionRouteChange, object: AVAudioSession.sharedInstance())
@objc func handleAudioSessionRouteChange(notification:NSNotification){
let userInfo = notification.userInfo
guard userInfo != nil else {
return
}
if let reason = userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt{
if reason == AVAudioSessionRouteChangeReason.oldDeviceUnavailable.rawValue{//舊設(shè)備輸出端口移除
if let routeDescription = userInfo?[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription{
let portDescription = routeDescription.outputs[0]
if portDescription.portName == "耳機"{
self.audioPlayer?.pause()
}
}
}else if reason == AVAudioSessionRouteChangeReason.newDeviceAvailable.rawValue{//新設(shè)備輸出端口接入
let routeDescription = AVAudioSession.sharedInstance().currentRoute
let portDescription = routeDescription.outputs[0]
if portDescription.portName == "耳機",audioPlayer != nil,selIndex>=0{
self.audioPlayer?.play()
}
}
}
}
切換聲道
func resetAuidoSession(isRecord:Bool) {
let audioSession = AVAudioSession.sharedInstance()
do{
try audioSession.setCategory(isRecord ? AVAudioSessionCategoryPlayAndRecord : AVAudioSessionCategoryPlayback)
try audioSession.setActive(true)
}catch{
}
}
參考鏈接:AVAudioPlayer