Swift实现iOS录音与播放音频功能
- 作用
AVPLayer:可以用来播放在线及本地音视频
AVAudioSession:音频会话,主要用来管理音频设置与硬件交互
使用时需要导入
#import <AVFoundation/AVFoundation.h>
- AVAudioSession中配置选项:
AVAudioSessionCategory
注意:除了 AVAudioSessionCategoryMultiRoute 外,其他的 Category 都遵循 last in wins 原则,即最后接入的音频设备作为输入或输出的主设备。
1.AVAudioSessionCategoryAmbient
当前App的播放声音可以和其他app播放的声音共存,当锁屏或按静音时停止。
2.AVAudioSessionCategorySoloAmbient
只能播放当前App的声音,其他app的声音会停止,当锁屏或按静音时停止。
3.AVAudioSessionCategoryPlayback
只能播放当前App的声音,其他app的声音会停止,当锁屏或按静音时不会停止。
4.AVAudioSessionCategoryRecord
只能用于录音,其他app的声音会停止,当锁屏或按静音时不会停止
5.AVAudioSessionCategoryPlayAndRecord
在录音的同时播放其他声音,当锁屏或按静音时不会停止
可用于听筒播放,比如微信语音消息听筒播放
6.AVAudioSessionCategoryAudioProcessing
使用硬件解码器处理音频,该音频会话使用期间,不能播放或录音
7.AVAudioSessionCategoryMultiRoute
多种音频输入输出,例如可以耳机、USB设备同时播放等
AVAudioSessionCategoryOptions
1.AVAudioSessionModeDefault
默认的模式,适用于所有的场景,可用于场景还原
2.AVAudioSessionModeVoiceChat
适用类别 :
AVAudioSessionCategoryPlayAndRecord
应用场景VoIP
3.AVAudioSessionModeGameChat
适用类别:
AVAudioSessionCategoryPlayAndRecord
应用场景游戏录制,由GKVoiceChat自动设置,无需手动调用
4.AVAudioSessionModeVideoRecording
适用类别:
AVAudioSessionCategoryPlayAndRecord
AVAudioSessionCategoryRecord
应用场景视频录制
5.AVAudioSessionModeMoviePlayback
适用类别:
AVAudioSessionCategoryPlayBack
应用场景视频播放
6.AVAudioSessionModeVideoChat
适用类别:
AVAudioSessionCategoryPlayAndRecord
应用场景视频通话
7.AVAudioSessionModeMeasurement
适用类别:
AVAudioSessionCategoryPlayAndRecord
AVAudioSessionCategoryRecord
AVAudioSessionCategoryPlayback
AVAudioSessionModeSpokenAudio
AVAudioSessionMode
1.AVAudioSessionCategoryOptionMixWithOthers
适用于:
AVAudioSessionCategoryPlayAndRecord
AVAudioSessionCategoryPlayback
AVAudioSessionCategoryMultiRoute
用于可以和其他app进行混音
2.AVAudioSessionCategoryOptionDuckOthers
适用于:
AVAudioSessionCategoryAmbient
AVAudioSessionCategoryPlayAndRecord
AVAudioSessionCategoryPlayback
AVAudioSessionCategoryMultiRoute
用于压低其他声音播放的音量,使期音量变小
3.AVAudioSessionCategoryOptionAllowBluetooth
适用于:
AVAudioSessionCategoryRecord and AVAudioSessionCategoryPlayAndRecord
用于是否支持蓝牙设备耳机等
4.AVAudioSessionCategoryOptionDefaultToSpeaker
适用于:
AVAudioSessionCategoryPlayAndRecord
用于将声音从Speaker播放,外放,即免提
5.AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers
适用于:
AVAudioSessionCategoryPlayAndRecord
AVAudioSessionCategoryPlayback
AVAudioSessionCategoryMultiRoute
6.AVAudioSessionCategoryOptionAllowBluetoothA2DP
适用于:
AVAudioSessionCategoryPlayAndRecord
蓝牙和a2dp
7.AVAudioSessionCategoryOptionAllowAirPlay
适用于:
AVAudioSessionCategoryPlayAndRecord
airplay
Swift实现iOS录音与播放音频功能
狂奔的胖蜗牛 关注
2017.05.01 15:41* 字数 97 阅读 4275评论 2喜欢 6
自己写的一个类,用于swift实现了录音与播放录制的音频的功能。详细的注意点见注释:
import Foundation
import AVFoundation
class RecordManager {
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)")
}
}
}
使用的时候,只需要在要录音的地方导入该类,初始化后,使用即可
let recoder_manager = RecordManager()//初始化
recoder_manager.beginRecord()//开始录音
recoder_manager.stopRecord()//结束录音
recoder_manager.play()//播放录制的音频
更多的功能,就需要看各自的项目需求,然后去做相应的修改了。
将原生社交分享整合到应用中
import UIKit
import Social
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let serviceType = SLServiceTypeTwitter
if SLComposeViewController.isAvailable(forServiceType: serviceType) {
let controller = SLComposeViewController(forServiceType: serviceType)
controller?.setInitialText("设置想与别人分享的文字")
controller?.add(UIImage(named: "风向文章中附带的图片"))
controller?.add(NSURL(string: "为分享文字和图片添加一个URL")! as URL)
controller?.completionHandler = {
(result: SLComposeViewControllerResult) in
print("completed")
}
}
}
}
播放音频文件和录音
//
// ViewController.swift
// SwiftExample
//
// Created by administrator on 2019/2/15.
// Copyright © 2019 administrator. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController,AVAudioPlayerDelegate,AVAudioRecorderDelegate {
var audioPlayer: AVAudioPlayer?
var audioRecoder: AVAudioRecorder?
/**通知消息,播放器完成播放音频文件的通知**/
func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flay: Bool) {
print("Finish playing the song")
}
override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.global().async {[weak self] in
self?.playAudio()
}
let workItem = DispatchWorkItem{
self.playAudio()
}
DispatchQueue.global().async(execute: workItem)
//录音
let session = AVAudioSession.sharedInstance()
do {
if #available(iOS 10.0, *) {
try session.setCategory(.playAndRecord, mode: .default, options: .duckOthers)
} else {
try session.setMode(.default)
try session.setActive(true, options: .notifyOthersOnDeactivation)
}
session.requestRecordPermission { [weak self](allowed: Bool) in
if allowed {
self?.startRecordingAudio()
}else{
print("have no permission")
}
}
} catch let error as NSError {
print("error \(error)")
}
}
func playAudio() {
let mainBundle = Bundle.main
let filePath = mainBundle.path(forResource: "MySong", ofType: ".mp3")
if let path = filePath {
let fileData = NSData(contentsOf: URL(fileURLWithPath: path))
var error: NSError
do {
self.audioPlayer = try AVAudioPlayer(data: fileData! as Data)
// try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
if let player = self.audioPlayer{
player.delegate = self
if player.prepareToPlay() && player.play(){
print("play success")
} else {
print("play failor")
}
}
}catch let error as NSError{
if error != nil{
print("创建播放器失败")
self.audioPlayer = nil
}
}
}
}
func audioRecodingPath() -> NSURL {
let fileManager = FileManager()
var documentsFolderUrl:URL?
do {
documentsFolderUrl = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
} catch let error as NSError {
print("error \(error)")
}
return documentsFolderUrl?.appendingPathComponent("recording.m4a") as! NSURL
}
func audioRecordingSettings() -> NSDictionary {
//音频录制选项
return [AVFormatIDKey : kAudioFormatMPEG4AAC,
AVSampleRateKey : 16000.0 as NSNumber,
AVNumberOfChannelsKey : 1 as NSNumber,
AVEncoderAudioQualityKey : AVAudioQuality.low.rawValue as NSNumber]
}
func startRecordingAudio() {
let audioRecordingURL = self.audioRecodingPath()
do {
audioRecoder = try AVAudioRecorder(url: audioRecordingURL as URL, settings: self.audioRecordingSettings() as! [String : Any])
if let recorder = audioRecoder {
recorder.delegate = self
if recorder.prepareToRecord() && recorder.record(){
let delayInSeconds = 5.0
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayInSeconds) {
self.audioRecoder?.stop()
}
// DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + delayInSeconds){}
}else{
print("error")
}
}
} catch let error as NSError {
print("error \(error)")
}
}
}
Swift实现iOS录音与播放音频功能的更多相关文章
- Domain=NSOSStatusErrorDomain Code=1937337955 关于iOS录音AVAudioRecorder与音频播放AVAudioPlayer真机调试录音不能播放的问题
error:Domain=NSOSStatusErrorDomain Code=1937337955 ,这个错误很常见, 原因是因为我们需要调用另外一个AVAudioPlayer 的初始化方法,来确定 ...
- C# NAudio录音和播放音频文件-实时绘制音频波形图(从音频流数据获取,而非设备获取)
NAudio的录音和播放录音都有对应的类,我在使用Wav格式进行录音和播放录音时使用的类时WaveIn和WaveOut,这两个类是对功能的回调和一些事件触发. 在WaveIn和WaveOut之外还有对 ...
- C# NAudio录音和播放音频文件及实时绘制音频波形图(从音频流数据获取,而非设备获取)
下午写了一篇关于NAudio的录音.播放和波形图的博客,不太满意,感觉写的太乱,又总结了下 NAudio是个相对成熟.开源的C#音频开发工具,它包含录音.播放录音.格式转换.混音调整等功能.本次介绍主 ...
- 实战AudioToolbox--在iOS平台上播放音频
上午看了关于AudioToolbox.framework相关的资料,结合网上的资料对AudioToolbox的基本使用有了整体上的认识,上一篇文章 笔谈AudioToolbox(一) 中提到使用Aud ...
- 【iOS录音与播放】实现利用音频队列,通过缓存进行对声音的采集与播放
都说iOS最恶心的部分是流媒体,其中恶心的恶心之处更在即时语音. 所以我们先不谈即时语音,研究一下,iOS中声音采集与播放的实现. 要在iOS设备上实现录音和播放功能,苹果提供了简单的做法,那就是利用 ...
- iOS录音加播放.
现在发现的事实有: 如果没有蓝牙设备, 那么可以用下面的方法边录音, 边放音乐: 在录音按钮按下的时候: _avSession = [AVAudioSession sharedInstance]; ...
- .net简单录音和播放音频文件代码
本代码特点:不用DirectX ,对于C/S .B/S都适用. 方法: //mciSendStrin.是用来播放多媒体文件的API指令,可以播放MPEG,AVI,WAV,MP3,等等,下面介绍一下它的 ...
- ios平台cocos2d-x播放音频、视频、音效的Demo(支持网络视频)
最近由ios应用转做游戏,游戏开始时需要播放一个视频,由于本身cocos2d-x播放视频的相关库,在网上搜到的资料都不是很全,我自己试过在cocos2dx直接调用ios的MediaPlayer来播放, ...
- Android 录音和播放
今天工作上需要做一个一边录音一边播放的功能,大致原因是有一个外部设备输入音频到我们机器,然后我们机器需要马上把音频播放出来.所以了解了一些有关录音和播放的知识.接到这个任务的第一反应就是看看Andro ...
随机推荐
- python 阶乘函数
def num(n): if n == 1: return n return n*num(n-1) print(num(10)) 输出 3628800 该函数使用了递归函数的规则.return 后面为 ...
- redis的基本操作
redis是key-value的数据结构,每条数据都是⼀个键值对 键的类型是字符串 注意:键不能重复 值的类型分为五种: 字符串string 哈希hash 列表list 集合set 有序集合zset ...
- SciPy fftpack(傅里叶变换)
章节 SciPy 介绍 SciPy 安装 SciPy 基础功能 SciPy 特殊函数 SciPy k均值聚类 SciPy 常量 SciPy fftpack(傅里叶变换) SciPy 积分 SciPy ...
- DEDE后台升级后不显示编辑器
dede5.7不显示编辑器不能编辑文章的解决办法:进入系统后台系统配置-系统基本参数-核心设置将fck换成ckeditor保存,当然需要fck编辑器也可以到dede官网下载.dede5.7不显示编辑器 ...
- 蓝牙 BLE 协议学习: 001-BLE协议栈整体架构
背景 在深入BLE协议帧之前,我们先看一下BLE协议栈整体架构. 转载自:<深入浅出低功耗蓝牙(BLE)协议栈> 架构 如上图所述,要实现一个BLE应用,首先需要一个支持BLE射频的芯片, ...
- git使用问题一新建本地仓库添加远程合并推送
1,git远程新建仓库demo 2,git本地初始化仓库demo 3,git本地添加远程仓库 git remote add <name> <url> 4,git把远程仓库pul ...
- 蓝桥杯 能量项链 (区间dp)
问题描述 在Mars星球上,每个Mars人都随身佩带着一串能量项链.在项链上有N颗能量珠.能量珠是一颗有头标记与尾标记的珠子,这些标记对应着某个正整数.并且,对于相邻的两颗珠子,前一颗珠子的尾标记一定 ...
- 单片机ADC检测4-20mA电路,以及计算方法
单片机ADC检测4-20mA电路,以及计算方法 转载:https://www.hongchangzidonghua.com/?id=24 1,手里有一个4-20mA输出的压力传感器,假设测量范围是0M ...
- [Codeforces]1263B PIN Code
题目 A PIN code is a string that consists of exactly 444 digits. Examples of possible PIN codes: 70137 ...
- Day8 - E - The very same Munchhausen CodeForces - 1120E
A positive integer aa is given. Baron Munchausen claims that he knows such a positive integer nn tha ...