溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

iOS如何實現(xiàn)錄音轉(zhuǎn)碼MP3及轉(zhuǎn)碼BASE64上傳功能

發(fā)布時間:2021-06-30 12:51:53 來源:億速云 閱讀:218 作者:小新 欄目:移動開發(fā)

這篇文章給大家分享的是有關(guān)iOS如何實現(xiàn)錄音轉(zhuǎn)碼MP3及轉(zhuǎn)碼BASE64上傳功能的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

iOS 錄音轉(zhuǎn)碼MP3及轉(zhuǎn)碼BASE64上傳

一,開始錄音

NSLog(@"開始錄音");

[self startRecord];

- (void)startRecord
{
  //刪除上次生成的文件,保留最新文件
  NSFileManager *fileManager = [NSFileManager defaultManager];
  if ([NSTemporaryDirectory() stringByAppendingString:@"myselfRecord.mp3"]) {
    [fileManager removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:@"myselfRecord.mp3"] error:nil];
  }
  if ([NSTemporaryDirectory() stringByAppendingString:@"selfRecord.wav"]) {
    [fileManager removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:@"selfRecord.wav"] error:nil];
  }
  
  //開始錄音
  //錄音設(shè)置
  NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
  //設(shè)置錄音格式 AVFormatIDKey==kAudioFormatLinearPCM
  [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
  //設(shè)置錄音采樣率(Hz) 如:AVSampleRateKey==8000/44100/96000(影響音頻的質(zhì)量), 采樣率必須要設(shè)為11025才能使轉(zhuǎn)化成mp3格式后不會失真
  [recordSetting setValue:[NSNumber numberWithFloat:11025.0] forKey:AVSampleRateKey];
  //錄音通道數(shù) 1 或 2 ,要轉(zhuǎn)換成mp3格式必須為雙通道
  [recordSetting setValue:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
  //線性采樣位數(shù) 8、16、24、32
  [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
  //錄音的質(zhì)量
  [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
  
  //存儲錄音文件
  recordUrl = [NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingString:@"selfRecord.wav"]];
  
  //初始化
  audioRecorder = [[AVAudioRecorder alloc] initWithURL:recordUrl settings:recordSetting error:nil];
  //開啟音量檢測
  audioRecorder.meteringEnabled = YES;
  audioSession = [AVAudioSession sharedInstance];//得到AVAudioSession單例對象

  if (![audioRecorder isRecording]) {
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];//設(shè)置類別,表示該應(yīng)用同時支持播放和錄音
    [audioSession setActive:YES error:nil];//啟動音頻會話管理,此時會阻斷后臺音樂的播放.
    
    [audioRecorder prepareToRecord];
    [audioRecorder peakPowerForChannel:0.0];
    [audioRecorder record];
  }
}

二,停止錄音

[self endRecord];


 - (void)endRecord
 {
   [audioRecorder stop];             //錄音停止
   [audioSession setActive:NO error:nil];     //一定要在錄音停止以后再關(guān)閉音頻會話管理(否則會報錯),此時會延續(xù)后臺音樂播放
 }

三,轉(zhuǎn)碼成MP3

- (void)transformCAFToMP3 {
  mp3FilePath = [NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingString:@"myselfRecord.mp3"]];
  
  @try {
    int read, write;
    
    FILE *pcm = fopen([[recordUrl absoluteString] cStringUsingEncoding:1], "rb");  //source 被轉(zhuǎn)換的音頻文件位置
    fseek(pcm, 4*1024, SEEK_CUR);                          //skip file header
    FILE *mp3 = fopen([[mp3FilePath absoluteString] cStringUsingEncoding:1], "wb"); //output 輸出生成的Mp3文件位置
    
    const int PCM_SIZE = 8192;
    const int MP3_SIZE = 8192;
    short int pcm_buffer[PCM_SIZE*2];
    unsigned char mp3_buffer[MP3_SIZE];
    
    lame_t lame = lame_init();
    lame_set_in_samplerate(lame, 11025.0);
    lame_set_VBR(lame, vbr_default);
    lame_init_params(lame);
    
    do {
      read = (int)fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
      if (read == 0)
        write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
      else
        write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
      
      fwrite(mp3_buffer, write, 1, mp3);
      
    } while (read != 0);
    
    lame_close(lame);
    fclose(mp3);
    fclose(pcm);
  }
  @catch (NSException *exception) {
    NSLog(@"%@",[exception description]);
  }
  @finally {
    NSLog(@"MP3生成成功");
    base64Str = [self mp3ToBASE64];
  }
}

四,上傳需要轉(zhuǎn)碼BASE64

 - (NSString *)mp3ToBASE64{
   NSData *mp3Data = [NSData dataWithContentsOfFile:[NSTemporaryDirectory() stringByAppendingString:@"myselfRecord.mp3"]];
   NSString *_encodedImageStr = [mp3Data base64Encoding];
   NSLog(@"===Encoded image:\n%@", _encodedImageStr);
   return _encodedImageStr;
 }

備注:其中可以直接生成的.caf  .wav    有壓縮的MP3需要轉(zhuǎn)格式,不能直接錄音生成

感謝各位的閱讀!關(guān)于“iOS如何實現(xiàn)錄音轉(zhuǎn)碼MP3及轉(zhuǎn)碼BASE64上傳功能”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

ios
AI