swift之k录音和播放

import UIKit

import AVFoundation

class RecordManager: NSObject {

    var recorder: AVAudioRecorder?

    var player: AVAudioPlayer?

    let file_path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first?.appending("/record.wav")

    

    

    //开始录音

    func beginRecord() {

        let session = AVAudioSession.sharedInstance()

        //设置session类型

        do {

            try session.setCategory(AVAudioSessionCategoryPlayAndRecord)

        } catch let err{

            print("设置类型失败:\(err.localizedDescription)")

        }

        //设置session动作

        do {

            try session.setActive(true)

        } catch let err {

            print("初始化动作失败:\(err.localizedDescription)")

        }

        //录音设置,注意,后面需要转换成NSNumber,如果不转换,你会发现,无法录制音频文件,我猜测是因为底层还是用OC写的原因

        let recordSetting: [String: Any] = [AVSampleRateKey: NSNumber(value: 16000),//采样率

            AVFormatIDKey: NSNumber(value: kAudioFormatLinearPCM),//音频格式

            AVLinearPCMBitDepthKey: NSNumber(value: 16),//采样位数

            AVNumberOfChannelsKey: NSNumber(value: 1),//通道数

            AVEncoderAudioQualityKey: NSNumber(value: AVAudioQuality.min.rawValue)//录音质量

        ];

        //开始录音

        do {

            let url = URL(fileURLWithPath: file_path!)

            recorder = try AVAudioRecorder(url: url, settings: recordSetting)

            recorder!.prepareToRecord()

            recorder!.record()

            print("开始录音")

        } catch let err {

            print("录音失败:\(err.localizedDescription)")

        }

    }

    

    

    //结束录音

    func stopRecord() {

        if let recorder = self.recorder {

            if recorder.isRecording {

                print("正在录音,马上结束它,文件保存到了:\(file_path!)")

            }else {

                print("没有录音,但是依然结束它")

            }

            recorder.stop()

            self.recorder = nil

        }else {

            print("没有初始化")

        }

    }

    

    

    //播放

    func play() {

        do {

            player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: file_path!))

            print("歌曲长度:\(player!.duration)")

            player!.play()

        } catch let err {

            print("播放失败:\(err.localizedDescription)")

        }

    }

    

   

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值