AVFoundation

AVAudioRecorder

import UIKit
import AVFoundation

class ViewController: UIViewController {

    lazy var recordUrl:URL = {
        var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        path = path.appending("/record.caf")
        print(path)
        let url = URL(string: path)
        return url!
    }()

    lazy var record:AVAudioRecorder = {

        // setting : 录音的设置项
        // 录音参数设置(不需要掌握, 一些固定的配置)
        let configDic: [String: AnyObject] = [
            // 编码格式
            AVFormatIDKey: NSNumber(value: Int32(kAudioFormatLinearPCM)),
            // 采样率
            AVSampleRateKey: NSNumber(value: 11025.0),
            // 通道数
            AVNumberOfChannelsKey: NSNumber(value: 2),
            // 录音质量
            AVEncoderAudioQualityKey: NSNumber(value: Int32(AVAudioQuality.min.rawValue))
        ]

        let record = try? AVAudioRecorder(url: self.recordUrl, settings: configDic)

         // 准备录音(系统会给我们分配一些资源)
        record?.prepareToRecord()

        // 从未来的某个时间点, 开始录音(需要我们手动通过代码结束录音)
        // record.recordAtTime(record.deviceCurrentTime + 3)

        // 从现在开始录音, 录多久
        record?.record(forDuration: 10)
        return record!
    }()

    lazy var player:AVPlayer = {
        let player = AVPlayer(url: self.recordUrl)
        return player
    }()

    @IBAction func startRecord(_ sender: Any) {

            player.pause()

            record.record()

            print("开始录音")
    }

    @IBAction func stopRecord(_ sender: Any) {

        //模仿微信,如果录音时间太短则视为放弃录音
        if (record.currentTime.isLess(than: 2.0)) {
            print("录音时间太短")
            record.stop()
            record.deleteRecording()
        } else {
            record.stop()

            print("结束录音")

            player.play()
        }


    }

}

AudioServices 音效播放

import UIKit
import AVFoundation

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        guard let url = Bundle.main.url(forResource: "m_17.wav", withExtension: nil) else { return }
        let urlCF = url as CFURL

        //创建SystemSoundID
        var soundId:SystemSoundID = 0

        AudioServicesCreateSystemSoundID(urlCF, &soundId)

        //带振动的音效播放,真机测试
        AudioServicesPlayAlertSound(soundId)

        //单纯的音效播放
        AudioServicesPlaySystemSound(soundId)

        //带振动的音效播放播放完毕的回调,真机测试
        AudioServicesPlayAlertSoundWithCompletion(soundId) { 
            print("带振动的播放完毕")

            //释放
            AudioServicesDisposeSystemSoundID(soundId)
        }

        //单纯的音效播放完毕的回调
        AudioServicesPlayAlertSoundWithCompletion(soundId) { 
            print("播放完毕")

            //释放
            AudioServicesDisposeSystemSoundID(soundId)
        }
    }
}

封装一个音效播放的工具类

import UIKit
import AVFoundation

class AudioServiceTool: NSObject {

    class func AudioPlayWithAlert(forResource:String,soundId:Int,inCompletionBlock:@escaping (() -> Void)) {

        guard let url = Bundle.main.url(forResource: forResource, withExtension: nil) else { return }
        let urlCF = url as CFURL

        //创建SystemSoundID
        var soundId:SystemSoundID = SystemSoundID(soundId)

        AudioServicesCreateSystemSoundID(urlCF, &soundId)

        //带振动的音效播放,真机测试
        AudioServicesPlayAlertSound(soundId)

        //带振动的音效播放播放完毕的回调,真机测试
        AudioServicesPlayAlertSoundWithCompletion(soundId) {

            inCompletionBlock()

            print("播放完毕")

            //释放
            AudioServicesDisposeSystemSoundID(soundId)
        }
    }

    class func AudioPlayWithSystem(forResource:String,soundId:Int,inCompletionBlock:@escaping (() -> Void)) {

        guard let url = Bundle.main.url(forResource: forResource, withExtension: nil) else { return }
        let urlCF = url as CFURL

        //创建SystemSoundID
        var soundId:SystemSoundID = SystemSoundID(soundId)

        AudioServicesCreateSystemSoundID(urlCF, &soundId)

        //单纯的音效播放
        AudioServicesPlaySystemSound(soundId)

        //单纯的音效播放完毕的回调
        AudioServicesPlaySystemSoundWithCompletion(soundId) {

            inCompletionBlock()

            print("播放完毕")

            //释放
            AudioServicesDisposeSystemSoundID(soundId)
        }

    }

}

AVAudioPlayer

import UIKit
import AVFoundation

class ViewController: UIViewController {

    lazy var player:AVAudioPlayer = {

        let player = try! AVAudioPlayer(contentsOf: Bundle.main.url(forResource: "music", withExtension: "mp3")!)
        player.enableRate = true//是否支持倍速播放
        player.delegate = self
        return player
    }()

    //播放
    @IBAction func play(_ sender: Any) {
        player.play()
    }

    //暂停
    @IBAction func pause(_ sender: Any) {
        player.pause()
    }

    //快进
    @IBAction func forward(_ sender: Any) {
        player.currentTime += 15
    }

    //快退
    @IBAction func rewind(_ sender: Any) {
        player.currentTime -= 15
    }

    //停止
    @IBAction func stop(_ sender: Any) {
        player.stop()
    }

    //倍速播放
    @IBAction func fastPlay(_ sender: Any) {
        player.rate = 4
    }

    //音量调整
    @IBAction func volume(_ sender: UISlider) {
        player.volume = sender.value
    }

}

extension ViewController: AVAudioPlayerDelegate {

    //检测音乐播放完毕
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        print("音乐播放完毕")
    }

}

音乐后台播放

先勾选后台模式

调用如下方法即可

func playBackground() -> () {

    // 1. 获取音频会话
    let audioSession: AVAudioSession = AVAudioSession.sharedInstance()

    do {
        // 2. 设置会话类型
        try audioSession.setCategory(AVAudioSessionCategoryPlayback    )

        // 3. 激活会话
        try audioSession.setActive(true)

    }catch {
        print(error)
    }


}

听筒模式和扬声器模式切换

听筒模式

UIDevice.current.isProximityMonitoringEnabled = true //开启红外线功能

        let session = AVAudioSession()

        do{

            try session.setCategory(AVAudioSessionCategoryPlayAndRecord, with: [])

            try session.setActive(true)

        }catch{



        }

扬声器模式

UIDevice.current.isProximityMonitoringEnabled = true //开启红外线功能

        let session = AVAudioSession()

        do{

            try session.setCategory(AVAudioSessionCategoryPlayback, with: [])

            try session.setActive(true)

        }catch{



        }

results matching ""

    No results matching ""