音频播放AVFoundation框架

一、系统声音

ios应用中的提醒声音、游戏背景音乐等。可以播放的格式有CAF、AIF、WAV。

系统声音服务提供了一个API,但是没有操作声音和控制音量的功能,因此如果为多媒体或者游戏创建专门的声音,就不要使用系统声音服务。

其中支持三种类型:声音、提醒、震动。

1、首先导入AudioToolbox.framework框架。

2、系统声音服务不是通过类实现的,而是通过传统的C语言函数调用来触发播放操作。要播放音频需要使用两个函数AudioServicesCreateSystemSoundID和AudioServicePlaySystemSound。

// MARK: - 系统声音
    /*----- 系统声音 ------*/
    @IBAction func systemSound()
    {
        //建立的SystemSoundID对象
        var soundID: SystemSoundID = 0
        
        //获取声音文件地址
        let path = NSBundle.mainBundle().pathForResource("SaoMa", ofType: "wav")
        
        //地址转换
        let baseURL = NSURL(fileURLWithPath: path!)
        
        //赋值
        AudioServicesCreateSystemSoundID(baseURL , &soundID)
        
        //使用AudioServicesPlaySystemSound播放
        AudioServicesPlaySystemSound(soundID)
    }
/*----- 系统提醒 ------*/
    @IBAction func systemAlert()
    {
        //建立的SystemSoundID对象
        var soundID: SystemSoundID = 0
        
        //获取声音文件地址
        let path = NSBundle.mainBundle().pathForResource("SaoMa", ofType: "wav")
        
        //地址转换
        let baseURL = NSURL(fileURLWithPath: path!)
        
        //赋值
        AudioServicesCreateSystemSoundID(baseURL , &soundID)
        
        //使用AudioServicesPlayAlertSound播放
        AudioServicesPlayAlertSound(soundID)

    }
/*----- 系统震动 ------*/
    @IBAction func systemVibration()
    {
         //建立的SystemSoundID对象
        let soundID = SystemSoundID(kSystemSoundID_Vibrate)
        
        //使用AudioServicesPlaySystemSound播放
        AudioServicesPlaySystemSound(soundID)
    }

二、AV音频播放器

1、导入AVFoundation.framework。

2、声明一个AVAudioPlayer对象。

    @IBOutlet var timeLabel:UILabel!//播放的时间/总时间
    @IBOutlet var jinDuSlider:UISlider!//进度条
    var _timer:NSTimer!//定时器线程, 刷新进度条
let mp3Path = NSBundle.mainBundle().pathForResource("xiaoPingGuo", ofType: "mp3")
        let fileUrl = NSURL.fileURLWithPath(mp3Path!)
        do
        {
            audioPlayer = try AVAudioPlayer(contentsOfURL: fileUrl)
        }
        catch let error as NSError {
            print("初始化播放器失败:(error)")//如果失败,error 会返回错误信息
        }
        audioPlayer.prepareToPlay()
//播放按钮事件
    @IBAction func audioPlayButton()
    {
        if audioPlayer.playing
        {
            return;//如果已在播放,跳出
        }
        
        //开始播放音频文件
        audioPlayer.play()
        
        //设置进图条最小是=0
        jinDuSlider.minimumValue = 0.0;
        
        //设置进度条最大值等于声音的描述
        jinDuSlider.maximumValue = Float(audioPlayer.duration)
        
        //启动定时器 定时更新进度条和时间label 在updateTime方法中实现
        _timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "updateTime", userInfo: nil, repeats: true)
    }
//定时器-
    func updateTime()
    {
        //获取音频播放器播放的进度,单位秒
        let cuTime:Float = Float(audioPlayer.currentTime)
        
        //更新进度条
        jinDuSlider.value = cuTime
        
        //获取总时间
        let duTime:Float = Float(audioPlayer.duration)
        
        //播放时间秒数,换算成:时、分、秒
        let hour1:Int = Int(cuTime/(60*60))
        let minute1:Int = Int(cuTime/60)
        let second1:Int = Int(cuTime%60)
        
        //总时间秒数,换算成:时、分、秒
        let hour2:Int = Int(duTime/(60*60))
        let minute2:Int = Int(duTime/60)
        let second2:Int = Int(duTime%60)
        
        
        //label显示
        timeLabel.text = NSString(format: "%.2d:%.2d:%.2d / %.2d:%.2d:%.2d",hour1,minute1,second1,hour2,minute2,second2) as String
    }

//
播放代理 AVAudioPlayerDelegate func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) { //成功播放完毕结束 } func audioPlayerDecodeErrorDidOccur(player: AVAudioPlayer, error: NSError?) { //音频播放器的解码错误 } //@availability(iOS, introduced=2.2, deprecated=8.0) func audioPlayerBeginInterruption(player: AVAudioPlayer) { //音频播放器开始中断 } //@availability(iOS, introduced=6.0, deprecated=8.0) func audioPlayerEndInterruption(player: AVAudioPlayer, withOptions flags: Int) { //音频播放结束中断 }
//暂停
    @IBAction func audioPauseButton(sender:UIButton)
    {
        let title = sender.titleForState(UIControlState.Normal)
        if  title == "Pause" && audioPlayer.playing
        {
            audioPlayer.pause()
            sender.setTitle("Continue", forState: UIControlState.Normal)
        }
        else if title == "Continue"
        {
            sender.setTitle("Pause", forState: UIControlState.Normal)
            audioPlayer.play()
        }
    }
    
    //停止
    @IBAction func audioStopButton(sender:UIButton)
    {
        if(audioPlayer.playing)
        {
            audioPlayer.stop()
            audioPlayer.currentTime=0;
            timeLabel.text = "";
        }
    }
    
    //调 进度
    @IBAction func jinDuChange(sender:UISlider)
    {
        //获取jinDuSlider的值来设置音频播放器进度
        print("当前进度:(jinDuSlider.value)")
        audioPlayer.currentTime = NSTimeInterval(jinDuSlider.value)
        
        //播放器播放
        audioPlayer.play()
    }

    //控制声音
    @IBAction func audioSoundChange(sender:UISlider)
    {
        //获取UISlider对象的值,并设置audioPlayer.volume
        audioPlayer.volume = sender.value
        
        aLabel.text = "(sender.value)"
    }
原文地址:https://www.cnblogs.com/fengmin/p/5714028.html