IOS开发实现录音功能
程序员文章站
2023-11-04 13:41:34
导入框架:
#import
声明全局变量:
@interface...
导入框架:
#import <avfoundation/avfoundation.h>
声明全局变量:
@interface viewcontroller ()<avaudiorecorderdelegate> { avaudiorecorder *audiorecorder; } @end
在viewdidload中:
uibutton *button = [uibutton buttonwithtype:uibuttontypecustom]; button.frame = cgrectmake(100, 100, 100, 100); [button settitle:@"tick" forstate:uicontrolstatenormal]; button.backgroundcolor = [uicolor browncolor]; [button addtarget:self action:@selector(startaudiorecoder:) forcontrolevents:uicontroleventtouchupinside]; [self.view addsubview:button];
按钮的触发事件
- (void)startaudiorecoder:(uibutton *)sender{ sender.selected = !sender.selected; if (sender.selected != yes) { [audiorecorder stop]; return; } // url是本地的url avaudiorecorder需要一个存储的路径 nsstring *name = [nsstring stringwithformat:@"%d.aiff",(int)[nsdate date].timeintervalsince1970]; nsstring *path = [nssearchpathfordirectoriesindomains(nscachesdirectory, nsuserdomainmask, yes).firstobject stringbyappendingpathcomponent:name]; nserror *error; // 录音机 初始化 audiorecorder = [[avaudiorecorder alloc]initwithurl:[nsurl fileurlwithpath:path] settings:@{avnumberofchannelskey:@2,avsampleratekey:@44100,avlinearpcmbitdepthkey:@32,avencoderaudioqualitykey:@(avaudioqualitymax),avencoderbitratekey:@128000} error:&error]; [audiorecorder preparetorecord]; [audiorecorder record]; audiorecorder.delegate = self; /* 1.avnumberofchannelskey 通道数 通常为双声道 值2 2.avsampleratekey 采样率 单位hz 通常设置成44100 也就是44.1k 3.avlinearpcmbitdepthkey 比特率 8 16 24 32 4.avencoderaudioqualitykey 声音质量 ① avaudioqualitymin = 0, 最小的质量 ② avaudioqualitylow = 0x20, 比较低的质量 ③ avaudioqualitymedium = 0x40, 中间的质量 ④ avaudioqualityhigh = 0x60,高的质量 ⑤ avaudioqualitymax = 0x7f 最好的质量 5.avencoderbitratekey 音频编码的比特率 单位kbps 传输的速率 一般设置128000 也就是128kbps */ nslog(@"%@",path); }
代理方法:
- (void)audiorecorderdidfinishrecording:(avaudiorecorder *)recorder successfully:(bool)flag{ nslog(@"录音结束"); // 文件操作的类 nsfilemanager *manger = [nsfilemanager defaultmanager]; nsstring *path = [nssearchpathfordirectoriesindomains(nscachesdirectory, nsuserdomainmask, yes) lastobject]; // 获得当前文件的所有子文件subpathsatpath nsarray *pathllist = [manger subpathsatpath:path]; // 需要只获得录音文件 nsmutablearray *audiopathlist = [nsmutablearray array]; // 遍历所有这个文件夹下的子文件 for (nsstring *audiopath in pathllist) { // 通过对比文件的延展名(扩展名 尾缀) 来区分是不是录音文件 if ([audiopath.pathextension isequaltostring:@"aiff"]) { // 把筛选出来的文件放到数组中 [audiopathlist addobject:audiopath]; } } nslog(@"%@",audiopathlist); }
上一篇: 如何煮甜品,在家也能做的暖心甜品