iOS錄音和播放上傳和下載動畫滿足60秒內的需求

道明白發表於2016-11-06

錄音功能研究了一週 總結的簡單的錄音和播放  滿足錄音60秒以內的上傳和下載

用的AVFoundation框架中的 AVAudioRecorder 進行錄音  用 AVAudioPlayer進行的播放 

錄音的格式選用的是AAC的,iOS , 安卓可以播放,伺服器需要轉成MP3播放

錄音程式碼

AVAudioSession *session = [AVAudioSession sharedInstance];//控制整個系統

NSError *sessionError;

[session setCategory:AVAudioSessionCategoryRecord error:&sessionError];//播放的時候用的AVAudioSessionCategoryPlayback

if (sessionError) {

NSLog(@”設定AVAudioSession大管家的時候報的錯_____%@”,sessionError.description);

}//判斷後臺有沒有播放

if (session == nil) {

NSLog(@”AVAudioSession後臺有播放:%@”, [sessionError description]);

} else {

[session setActive:YES error:nil];

}

[self.recorder record];

準備錄音配置

– (AVAudioRecorder *)recorder {

if (_recorder == nil) {

NSMutableDictionary* recordSettingAAC = [[NSMutableDictionary alloc] init];

[recordSettingAAC setValue :[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];//AAC 格式的壓縮比和品質都是實用的,檔案小音質高    AAC(Advanced Audio Coding),中文名:高階音訊編碼,出現於1997年,基於MPEG-2的音訊編碼技術。由Fraunhofer IIS、杜比實驗室、AT&T、Sony等公司共同開發,目的是取代MP3格式。2000年,MPEG-4標準出現後,AAC重新整合了其特性,加入了SBR技術和PS技術,為了區別於傳統的MPEG-2 AAC又稱為MPEG-4 AAC。http://www.mamicode.com/info-detail-986202.html

[recordSettingAAC setValue:[NSNumber numberWithFloat:32000.0] forKey:AVSampleRateKey];//設定錄音取樣率(Hz) 如:AVSampleRateKey==8000/44100/96000(影響音訊的質量), 此處取樣頻率設定成8000就夠用,我們們打電話的取樣平率就是8000 設定成32000 是因為後臺轉MP3時的限制

[recordSettingAAC setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];//錄音通道數  1 或 2 ,要轉換成mp3格式必須為雙通道

[recordSettingAAC setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];

// [recordSettingAAC setValue:[NSNumber numberWithInt:16] forKey:AVEncoderBitRateKey];//ios7 可以  ios9 以上設定這句話會閃退

[recordSettingAAC setObject:@(8) forKey:AVLinearPCMBitDepthKey]; //線性取樣位數  8、16、24、32

[recordSettingAAC setObject:@(YES) forKey:AVLinearPCMIsFloatKey]; //是否使用浮點數取樣

NSError *error;

_recorder = [[AVAudioRecorder alloc] initWithURL:self.urlRecordFile settings:recordSettingAAC error:&error];

if (error || self.recorder == nil) {

NSLog(@”錄音建立時候的錯誤___%@”,error.description);

}

_recorder.delegate = self;

_recorder.meteringEnabled = YES;

[_recorder prepareToRecord];

}

return _recorder;

}

我將錄音檔案 存在 tem 臨時檔案

– (NSURL *)urlRecordFile

{

if (_urlRecordFile == nil) {

_urlRecordFile = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:@TmpFile.aac”]];//注意字尾 一定要加上mac 否則上傳給伺服器他們不能判斷檔案型別導致檔案播放失敗   

}

return _urlRecordFile;

}

錄音成功後上傳給伺服器:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];   

 manager.responseSerializer    = [AFHTTPResponseSerializer serializer];   

 manager.requestSerializer    = [AFHTTPRequestSerializer serializer];  

  manager.requestSerializer.timeoutInterval = 10;    

//上傳檔案流 

   [manager POST:urlString parameters:dictionary constructingBodyWithBlock:^(idformData) {

[formData appendPartWithFileData:dataVoice name:@”file” fileName:@”text.aac” mimeType:@”audio/mpeg3″];

//NSData *dataVoice = [NSData dataWithContentsOfURL: self.urlRecordFile]];

} success:^(NSURLSessionDataTask *task, id responseObject) {

NSError * error = nil;

NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];

if (!error) {

} else {

}

} failure:^(NSURLSessionDataTask *task, NSError *error) {

}];

下載:

NSData *dataAudio = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];

播放:

AVAudioSession *session = [AVAudioSession sharedInstance];//控制整個系統

NSError *sessionError;

[session setCategory:AVAudioSessionCategoryPlayback error:&sessionError];

NSError *playError;

//NSData *data =  [NSData dataWithContentsOfURL:self.urlRecordFile];本地的資料也可以進行播放

self.player = [[AVAudioPlayer alloc] initWithData:dataAudio error:&playError];

self.player.delegate = self;

//當播放錄音為空, 列印錯誤資訊

if (self.player == nil) {

NSLog(@”播放器的問題: %@”, [playError description]);

}

[self.player play];

下面說說錄音檔案的大小

[recordSettingAAC setValue:[NSNumber numberWithFloat:16000.0] forKey:AVSampleRateKey];取樣率是16000 蘋果4s 60秒 369kb  效能好的手機相應的錄音檔案會大點 

[recordSettingAAC setValue:[NSNumber numberWithFloat:8000.0] forKey:AVSampleRateKey];取樣率是8000 的4s 60秒 250kb  

取樣率越大對應的錄音的檔案就越大,因為取樣率大 就意味著取樣的頻率越高,取樣的錄音更加接近原聲。32000的取樣率 生成的錄音檔案大概是800kb 左右 

類似QQ錄音那樣根據音量大小展示的相應的動畫的程式碼如下:

錄音的時候開啟定時器:

_timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateImage) userInfo:nil repeats:YES];

[_timer fire];

– (void)updateImage {

[self.recorder updateMeters];

double lowPassResults = pow(10, (0.05 * [self.recorder peakPowerForChannel:0]));

float result  = 10 * (float)lowPassResults;

NSLog(@”音量%f”, result);

    int no = 1;

    if (result > 0 && result <= 1.5) {

       no = 1;

    } else if (result > 1.5 && result <= 2.5) {

        no = 2;

    } else if (result > 2.5 && result <= 3.5) {

        no = 3;

    } else if (result > 3.5 && result <= 5.0) {

      no = 4;

   } else if (result > 5.0 && result <= 8) {

      no = 5;

   } else if (result > 8 ) {

        no = 6;

   }

}

//根據音量的大小做相應的幀動畫

self.imaViewLeft.animationDuration = 0.5;//和取聲音的頻率一致

self.imaViewLeft.animationImages = [self arrayImageAnimationLeftWithNum:num];//這句話是指給imageview新增動畫的圖片

[self.imaViewLeft startAnimating];

//圖片陣列

– (NSMutableArray *)arrayImageAnimationRightWithNum:(int)num

{

_arrayImageAnimation = [NSMutableArray arrayWithCapacity:0];

for (int i = 6; i > 0; i–)

{

NSString *str = [NSString stringWithFormat:@”animation_%d_%d”,num,i];

UIImage  *image = [UIImage imageNamed:str];

[_arrayImageAnimation addObject:image];

}

return _arrayImageAnimation;

}


相關文章