2014/01/16

Audio Recording in Android and IOS

目前錄音在手機中是很普遍的功能,android 系統已內建錄音app,iPhone也有內建語音備忘錄,其他也有許多關於電話錄音的app出現。但如果今天您希望能將錄音檔傳給別人,尤其是跨系統的傳輸,如何讓您傳輸的檔案在對方的平台也能正常播放呢?下面就來介紹一下如何選擇錄音格式讓音訊檔可跨平台播放
Android支援的「錄音」格式:AMR、3GP...(詳情請見 Android Developer )
iPhone支援的「錄音」格式:AAC、WAV...(詳情請見 Apple Developer )
Android支援的「音訊播放」格式:AMR、3GP、WAV...(詳情請見 Android Developer )
iPhone支援的「音訊播放」格式:AAC、WAV、MP4...(詳情請見 Apple Developer )
IOS 不支援 AMR 音訊播放,必須轉成 WAV 等音訊格式才能播放,Android 支援 AMR 與 WAV 音訊格式的播放,但考慮到錄音檔案大小,故這裡選用 AMR 錄音格式

Code解說

Android AMR 錄音

//設定錄音檔名
SimpleDateFormat ff = new SimpleDateFormat("yyyy-MM-dd_hh_mm_ss");
String now = ff.format(new Date());
rfilename = "";

if (rfilename.equals("")) {
 rfilename = now + ".amr";
}
try {
 File SDCardpath = Environment.getExternalStorageDirectory();
 //路徑:/mnt/sdcard/download/2497_2013-10-12_01_19_00.amr
 File myDataPath = new File( SDCardpath.getAbsolutePath() + "/download" );
 if( !myDataPath.exists() ){
  myDataPath.mkdirs();
 }
 rfilePath = SDCardpath.getAbsolutePath() + "/download/" + rfilename;
 recodeFile = new File(rfilePath);
 
 mediaRecorder = new MediaRecorder();
 //設定音源
 mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
 //設定輸出檔案的格式
 mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
 //設定編碼格式
 mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
 //設定錄音檔位置
 mediaRecorder.setOutputFile(recodeFile.getAbsolutePath());
 
 mediaRecorder.prepare();
 
 //開始錄音
 mediaRecorder.start();

} catch (IOException e) {
 e.printStackTrace();
}
iPhone WAV 錄音( ios 自 4.3 開始不支援 amr 音訊格式,故選擇 WAV 檔)

//init
NSString *filename = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"recorder.wav"];
NSURL *url = [NSURL fileURLWithPath:filename];

NSDictionary *settings = [[NSDictionary alloc] initWithObjectsAndKeys:
                          [NSNumber numberWithFloat: 8000.0],AVSampleRateKey, //采樣率
                          [NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,
                          [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,//采樣位數
                          [NSNumber numberWithInt: 1], AVNumberOfChannelsKey,//通道的數目
                          nil];
NSError *err = nil;
self.recoeder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&err];

if(err!=nil){
    NSLog(@"err=%@",err);
}

self.recoeder.delegate = self;
self.recoeder.meteringEnabled = YES;
[self.recoeder prepareToRecord];

//啟用音訊會話
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayAndRecord error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride);

//開始錄音
[self.recoeder record];
接著就可以將錄好的 AMR 或 WAV 檔案傳輸給對方瞜! 至於錄音檔的播放請見下篇 Play AMR and WAV files from Android IOS and Browser

References

沒有留言:

張貼留言