iOS 实时录音和播放
需求:最近公司需要做一個樓宇對講的功能:門口機(連接WIFI)撥號對室內機(對應的WIFI)的設備進行呼叫,室內機收到呼叫之后將對收到的數據進行UDP廣播的轉發,手機(連接對應的WIFI)收到視頻流之后,實時的展示視頻數據(手機可以接聽,掛斷,手機接聽之后,室內機不展示視頻,只是進行轉發。)
簡單點說就是手機客戶端需要做一個類似于直播平臺的軟件,可以實時的展示視頻,實時的播放接收到的聲音數據,并且實時將手機麥克風收到的聲音回傳給室內機,室內機負責轉發給門口機。
?
這篇文章介紹iOS怎么進行實時的錄音和播放收到的聲音數據?
?
想要使用系統的框架實時播放聲音和錄音數據,就得知道音頻隊列服務,
在AudioToolbox框架中的音頻隊列服務,它完全可以做到音頻播放和錄制,
一個音頻服務隊列有三個部分組成:
1.三個緩沖器Buffers:每個緩沖器都是一個存儲音頻數據的臨時倉庫。
2.一個緩沖隊列Buffer Queue:一個包含音頻緩沖器的有序隊列。
3.一個回調CallBack:一個自定義的隊列回調函數。
?具體怎么運轉的還是百度吧!
我的簡單理解:
對于播放:系統會自動從緩沖隊列中循環取出每個緩沖器中的數據進行播放,我們需要做的就是將接收到的數據循環的放到緩沖器中,剩下的就交給系統去實現了。
對于錄音: ?系統會自動將錄的聲音放入隊列中的每個緩沖器中,我們需要做的就是從回調函數中將數據轉化我們自己的數據就OK了。
?
#pragma mark--實時播放
1. 導入系統框架AudioToolbox.framework ?AVFoundation.framework
2. 獲取麥克風權限,在工程的Info.plist文件中加入Privacy - Microphone Usage Description 這個key 描述:App想要訪問您的麥克風
3. 創建播放聲音的類 EYAudio
?
EYAudio.h
#import <Foundation/Foundation.h>@interface EYAudio : NSObject// 播放的數據流數據 - (void)playWithData:(NSData *)data;// 聲音播放出現問題的時候可以重置一下 - (void)resetPlay;// 停止播放 - (void)stop;@end?
?EYAudio.m
?
#import "EYAudio.h" #import <AVFoundation/AVFoundation.h> #import <AudioToolbox/AudioToolbox.h>#define MIN_SIZE_PER_FRAME 1920 //每個包的大小,室內機要求為960,具體看下面的配置信息 #define QUEUE_BUFFER_SIZE 3 //緩沖器個數 #define SAMPLE_RATE 16000 //采樣頻率@interface EYAudio(){AudioQueueRef audioQueue; //音頻播放隊列 AudioStreamBasicDescription _audioDescription;AudioQueueBufferRef audioQueueBuffers[QUEUE_BUFFER_SIZE]; //音頻緩存BOOL audioQueueBufferUsed[QUEUE_BUFFER_SIZE]; //判斷音頻緩存是否在使用NSLock *sysnLock;NSMutableData *tempData;OSStatus osState; } @end@implementation EYAudio#pragma mark - 提前設置AVAudioSessionCategoryMultiRoute 播放和錄音 + (void)initialize {NSError *error = nil;//只想要播放:AVAudioSessionCategoryPlayback//只想要錄音:AVAudioSessionCategoryRecord//想要"播放和錄音"同時進行 必須設置為:AVAudioSessionCategoryMultiRoute 而不是AVAudioSessionCategoryPlayAndRecord(設置這個不好使)BOOL ret = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryMultiRoute error:&error];if (!ret) {NSLog(@"設置聲音環境失敗");return;}//啟用audio sessionret = [[AVAudioSession sharedInstance] setActive:YES error:&error];if (!ret){NSLog(@"啟動失敗");return;} }- (void)resetPlay {if (audioQueue != nil) {AudioQueueReset(audioQueue);} }- (void)stop {if (audioQueue != nil) {AudioQueueStop(audioQueue,true);}audioQueue = nil;sysnLock = nil; }- (instancetype)init {self = [super init];if (self) {sysnLock = [[NSLock alloc]init];//設置音頻參數 具體的信息需要問后臺_audioDescription.mSampleRate = SAMPLE_RATE;_audioDescription.mFormatID = kAudioFormatLinearPCM;_audioDescription.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;//1單聲道_audioDescription.mChannelsPerFrame = 1;//每一個packet一偵數據,每個數據包下的楨數,即每個數據包里面有多少楨_audioDescription.mFramesPerPacket = 1;//每個采樣點16bit量化 語音每采樣點占用位數_audioDescription.mBitsPerChannel = 16;_audioDescription.mBytesPerFrame = (_audioDescription.mBitsPerChannel / 8) * _audioDescription.mChannelsPerFrame;//每個數據包的bytes總數,每楨的bytes數*每個數據包的楨數_audioDescription.mBytesPerPacket = _audioDescription.mBytesPerFrame * _audioDescription.mFramesPerPacket;// 使用player的內部線程播放 新建輸出AudioQueueNewOutput(&_audioDescription, AudioPlayerAQInputCallback, (__bridge void * _Nullable)(self), nil, 0, 0, &audioQueue);// 設置音量AudioQueueSetParameter(audioQueue, kAudioQueueParam_Volume, 1.0);// 初始化需要的緩沖區for (int i = 0; i < QUEUE_BUFFER_SIZE; i++) {audioQueueBufferUsed[i] = false;osState = AudioQueueAllocateBuffer(audioQueue, MIN_SIZE_PER_FRAME, &audioQueueBuffers[i]);}osState = AudioQueueStart(audioQueue, NULL);if (osState != noErr) {NSLog(@"AudioQueueStart Error");}}return self; }// 播放數據 -(void)playWithData:(NSData *)data {[sysnLock lock];tempData = [NSMutableData new];[tempData appendData: data];NSUInteger len = tempData.length;Byte *bytes = (Byte*)malloc(len);[tempData getBytes:bytes length: len];int i = 0;while (true) {if (!audioQueueBufferUsed[i]) {audioQueueBufferUsed[i] = true;break;}else {i++;if (i >= QUEUE_BUFFER_SIZE) {i = 0;}}}audioQueueBuffers[i] -> mAudioDataByteSize = (unsigned int)len;// 把bytes的頭地址開始的len字節給mAudioData,向第i個緩沖器memcpy(audioQueueBuffers[i] -> mAudioData, bytes, len);// 釋放對象 free(bytes);//將第i個緩沖器放到隊列中,剩下的都交給系統了AudioQueueEnqueueBuffer(audioQueue, audioQueueBuffers[i], 0, NULL);[sysnLock unlock]; }// ************************** 回調 ********************************** // 回調回來把buffer狀態設為未使用 static void AudioPlayerAQInputCallback(void* inUserData,AudioQueueRef audioQueueRef, AudioQueueBufferRef audioQueueBufferRef) {EYAudio* audio = (__bridge EYAudio*)inUserData;[audio resetBufferState:audioQueueRef and:audioQueueBufferRef]; }- (void)resetBufferState:(AudioQueueRef)audioQueueRef and:(AudioQueueBufferRef)audioQueueBufferRef {// 防止空數據讓audioqueue后續都不播放,為了安全防護一下if (tempData.length == 0) {audioQueueBufferRef->mAudioDataByteSize = 1;Byte* byte = audioQueueBufferRef->mAudioData;byte = 0;AudioQueueEnqueueBuffer(audioQueueRef, audioQueueBufferRef, 0, NULL);}for (int i = 0; i < QUEUE_BUFFER_SIZE; i++) {// 將這個buffer設為未使用if (audioQueueBufferRef == audioQueueBuffers[i]) {audioQueueBufferUsed[i] = false;}} }@end?
?
外界使用: 不斷調用下面的方法將NSData傳遞進來
- (void)playWithData:(NSData *)data;?
?
?#pragma mark--實時錄音
?
1. 導入系統框架AudioToolbox.framework ?AVFoundation.framework
2. 創建錄音的類 EYRecord
?
EYRecord.h
?
#import <Foundation/Foundation.h>@interface ESARecord : NSObject//開始錄音 - (void)startRecording;//停止錄音 - (void)stopRecording;@end?
EYRecord.m
?
#import "ESARecord.h" #import <AudioToolbox/AudioToolbox.h>#define QUEUE_BUFFER_SIZE 3 // 輸出音頻隊列緩沖個數 #define kDefaultBufferDurationSeconds 0.03//調整這個值使得錄音的緩沖區大小為960,實際會小于或等于960,需要處理小于960的情況 #define kDefaultSampleRate 16000 //定義采樣率為16000extern NSString * const ESAIntercomNotifationRecordString;static BOOL isRecording = NO;@interface ESARecord(){AudioQueueRef _audioQueue; //輸出音頻播放隊列 AudioStreamBasicDescription _recordFormat;AudioQueueBufferRef _audioBuffers[QUEUE_BUFFER_SIZE]; //輸出音頻緩存 } @property (nonatomic, assign) BOOL isRecording;@end@implementation ESARecord- (instancetype)init {self = [super init];if (self) {//重置下memset(&_recordFormat, 0, sizeof(_recordFormat));_recordFormat.mSampleRate = kDefaultSampleRate;_recordFormat.mChannelsPerFrame = 1;_recordFormat.mFormatID = kAudioFormatLinearPCM;_recordFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;_recordFormat.mBitsPerChannel = 16;_recordFormat.mBytesPerPacket = _recordFormat.mBytesPerFrame = (_recordFormat.mBitsPerChannel / 8) * _recordFormat.mChannelsPerFrame;_recordFormat.mFramesPerPacket = 1;//初始化音頻輸入隊列AudioQueueNewInput(&_recordFormat, inputBufferHandler, (__bridge void *)(self), NULL, NULL, 0, &_audioQueue);//計算估算的緩存區大小int frames = (int)ceil(kDefaultBufferDurationSeconds * _recordFormat.mSampleRate);int bufferByteSize = frames * _recordFormat.mBytesPerFrame;NSLog(@"緩存區大小%d",bufferByteSize);//創建緩沖器for (int i = 0; i < QUEUE_BUFFER_SIZE; i++){AudioQueueAllocateBuffer(_audioQueue, bufferByteSize, &_audioBuffers[i]);AudioQueueEnqueueBuffer(_audioQueue, _audioBuffers[i], 0, NULL);}}return self; }-(void)startRecording {// 開始錄音 AudioQueueStart(_audioQueue, NULL);isRecording = YES; }void inputBufferHandler(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer, const AudioTimeStamp *inStartTime,UInt32 inNumPackets, const AudioStreamPacketDescription *inPacketDesc) {if (inNumPackets > 0) {ESARecord *recorder = (__bridge ESARecord*)inUserData;[recorder processAudioBuffer:inBuffer withQueue:inAQ];}if (isRecording) {AudioQueueEnqueueBuffer(inAQ, inBuffer, 0, NULL);} }- (void)processAudioBuffer:(AudioQueueBufferRef )audioQueueBufferRef withQueue:(AudioQueueRef )audioQueueRef {NSMutableData * dataM = [NSMutableData dataWithBytes:audioQueueBufferRef->mAudioData length:audioQueueBufferRef->mAudioDataByteSize];if (dataM.length < 960) { //處理長度小于960的情況,此處是補00Byte byte[] = {0x00};NSData * zeroData = [[NSData alloc] initWithBytes:byte length:1];for (NSUInteger i = dataM.length; i < 960; i++) {[dataM appendData:zeroData];}}// NSLog(@"實時錄音的數據--%@", dataM);//此處是發通知將dataM 傳遞出去[[NSNotificationCenter defaultCenter] postNotificationName:@"EYRecordNotifacation" object:@{@"data" : dataM}]; }-(void)stopRecording {if (isRecording){isRecording = NO;//停止錄音隊列和移除緩沖區,以及關閉session,這里無需考慮成功與否AudioQueueStop(_audioQueue, true);//移除緩沖區,true代表立即結束錄制,false代表將緩沖區處理完再結束AudioQueueDispose(_audioQueue, true);}NSLog(@"停止錄音"); }@end總結
以上是生活随笔為你收集整理的iOS 实时录音和播放的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 机器学习---数据简介及数据清洗概述
- 下一篇: 各硬盘编号含义