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//循环播放次数
audioPlayer.volume = 0.8//音量
audioPlayer.pan = 0.0 //切换声道 -1.0左声道 0 双声道 1.0 右声道
audioPlayer.delegate = self//
audioPlayer.play()
}catch{
}
AVAudioPlayerDelegate
//播放结束
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
}
//解码失败
func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
print("解码失败")
}
//中断开始
func audioPlayerBeginInterruption(_ player: AVAudioPlayer) {
}
//中断结束
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{//旧设备输出端口移除
if let routeDescription = userInfo?[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription{
let portDescription = routeDescription.outputs[0]
if portDescription.portName == "耳机"{
self.audioPlayer?.pause()
}
}
}else if reason == AVAudioSessionRouteChangeReason.newDeviceAvailable.rawValue{//新设备输出端口接入
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