AudioRecorder.m 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. // _____ _
  2. // |_ _| |_ _ _ ___ ___ _ __ __ _
  3. // | | | ' \| '_/ -_) -_) ' \/ _` |_
  4. // |_| |_||_|_| \___\___|_|_|_\__,_(_)
  5. //
  6. // Threema iOS Client
  7. // Copyright (c) 2015-2020 Threema GmbH
  8. //
  9. // This program is free software: you can redistribute it and/or modify
  10. // it under the terms of the GNU Affero General Public License, version 3,
  11. // as published by the Free Software Foundation.
  12. //
  13. // This program is distributed in the hope that it will be useful,
  14. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. // GNU Affero General Public License for more details.
  17. //
  18. // You should have received a copy of the GNU Affero General Public License
  19. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. #import "AudioRecorder.h"
  21. #import "AppDelegate.h"
  22. #ifdef DEBUG
  23. static const DDLogLevel ddLogLevel = DDLogLevelVerbose;
  24. #else
  25. static const DDLogLevel ddLogLevel = DDLogLevelWarning;
  26. #endif
  27. #define kMaxRecordDuration 1800.0
  28. #define kMaxSaveWaitTimeS 10.0
  29. #define kRecordFileName @"recordAudio"
  30. #define kRecordTmpFileName @"interrupted"
  31. @interface AudioRecorder () <AVAudioRecorderDelegate>
  32. @property NSURL *recordAudioUrl;
  33. @property NSURL *tmpRecorderFile;
  34. @property NSTimeInterval tmpFileDuration;
  35. @property dispatch_semaphore_t sema;
  36. @property BOOL interrupted;
  37. @end
  38. @implementation AudioRecorder
  39. - (void)dealloc {
  40. [self stop];
  41. [self unregisterFromNotifications];
  42. [self cleanupFiles];
  43. // make sure delegate methods are not called anymore
  44. _recorder.delegate = nil;
  45. }
  46. - (void)start {
  47. [self cleanupFiles];
  48. [self registerForNotifications];
  49. [self startRecording];
  50. }
  51. - (void)stop {
  52. [self stopRecorder];
  53. [self unregisterFromNotifications];
  54. [self joinWithTmpFile];
  55. }
  56. - (void)startRecording {
  57. [self setupRecorder];
  58. if ([_recorder recordForDuration:kMaxRecordDuration]) {
  59. DDLogInfo(@"Recording");
  60. [UIApplication sharedApplication].idleTimerDisabled = YES;
  61. }
  62. }
  63. - (void)stopRecorder {
  64. if (_recorder.recording) {
  65. [_recorder stop];
  66. }
  67. }
  68. - (NSURL *)audioURL {
  69. return [self recorderUrl];
  70. }
  71. - (void)cleanupFiles {
  72. /* ensure audio files are deleted */
  73. [[NSFileManager defaultManager] removeItemAtURL:_recordAudioUrl error:nil];
  74. [[NSFileManager defaultManager] removeItemAtURL:_tmpRecorderFile error:nil];
  75. _recordAudioUrl = nil;
  76. _tmpRecorderFile = nil;
  77. _tmpFileDuration = 0;
  78. }
  79. - (NSURL *)tmpAudioUrlWithFileNamed:(NSString *)filename {
  80. NSURL *tmpDirUrl = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
  81. NSURL *url = [[tmpDirUrl URLByAppendingPathComponent:filename] URLByAppendingPathExtension: MEDIA_EXTENSION_AUDIO];
  82. DDLogInfo(@"fileURL: %@", [url path]);
  83. return url;
  84. }
  85. - (void)setupRecorder {
  86. NSError *error = nil;
  87. [self stopRecorder];
  88. _recordAudioUrl = [self tmpAudioUrlWithFileNamed:kRecordFileName];
  89. NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] initWithCapacity:10];
  90. [recordSettings setObject:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
  91. [recordSettings setObject:[NSNumber numberWithFloat:22050.0] forKey: AVSampleRateKey];
  92. [recordSettings setObject:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];
  93. [recordSettings setObject:[NSNumber numberWithInt:32000] forKey:AVEncoderBitRateKey];
  94. [recordSettings setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
  95. [recordSettings setObject:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
  96. _recorder = [[AVAudioRecorder alloc] initWithURL:_recordAudioUrl settings:recordSettings error:&error];
  97. if (_recorder == nil) {
  98. DDLogError(@"Cannot create audio recorder: %@", error);
  99. [UIAlertTemplate showAlertWithOwner:[[AppDelegate sharedAppDelegate] currentTopViewController] title:error.localizedDescription message:error.localizedFailureReason actionOk:nil];
  100. return;
  101. }
  102. _recorder.delegate = self;
  103. }
  104. - (NSURL *)recorderUrl {
  105. return _recordAudioUrl;
  106. }
  107. - (BOOL)recording {
  108. return _recorder.recording;
  109. }
  110. - (NSTimeInterval)currentTime {
  111. return _recorder.currentTime + _tmpFileDuration;
  112. }
  113. #pragma mark - AVAudioRecorderDelegate
  114. - (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag {
  115. DDLogInfo(@"Finished recording, successfully: %d", flag);
  116. if (_interrupted) {
  117. _interrupted = NO;
  118. return;
  119. } else {
  120. [self stop];
  121. [_delegate recorderDidFinish];
  122. }
  123. }
  124. - (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error {
  125. DDLogError(@"Encode error: %@", error);
  126. }
  127. #pragma mark - Notifications
  128. - (void)registerForNotifications {
  129. NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
  130. [nc addObserver:self selector:@selector(avSessionInterrupted:)
  131. name:AVAudioSessionInterruptionNotification object:nil];
  132. [nc addObserver:self selector:@selector(applicationWillEnterForeground:)
  133. name:UIApplicationWillEnterForegroundNotification object:nil];
  134. }
  135. - (void)unregisterFromNotifications {
  136. [[NSNotificationCenter defaultCenter] removeObserver:self];
  137. }
  138. - (void)avSessionInterrupted:(NSNotification *)notification {
  139. NSNumber *interruptionType = [notification.userInfo objectForKey:@"AVAudioSessionInterruptionTypeKey"];
  140. DDLogInfo(@"AVAudioSessionInterruptionNotification: %d", interruptionType.intValue);
  141. if (interruptionType.intValue == AVAudioSessionInterruptionTypeBegan) {
  142. _interrupted = YES;
  143. _tmpFileDuration = self.currentTime;
  144. [_recorder stop];
  145. [self saveToTmpFile];
  146. } else {
  147. [self startRecording];
  148. [_delegate recorderResumedAfterInterrupt];
  149. }
  150. }
  151. - (void)applicationWillEnterForeground:(NSNotification*)notification {
  152. if (_interruptedAndNotStarted == true) {
  153. _interruptedAndNotStarted = false;
  154. [self startRecording];
  155. [_delegate recorderResumedAfterInterrupt];
  156. }
  157. }
  158. - (void)saveToTmpFile {
  159. // Do we already have a temporary recording? If so, join it with the current one
  160. if (_tmpRecorderFile) {
  161. AVMutableComposition *composition = [AVMutableComposition composition];
  162. AVAsset *asset = [AVURLAsset URLAssetWithURL:_tmpRecorderFile options:nil];
  163. CMTime timeZero = CMTimeMake(0, asset.duration.timescale);
  164. CMTimeRange timeRange = CMTimeRangeFromTimeToTime(timeZero, asset.duration);
  165. [composition insertTimeRange:timeRange ofAsset:asset atTime:timeZero error:nil];
  166. DDLogVerbose(@"join added: %f %@", CMTimeGetSeconds(asset.duration), _tmpRecorderFile);
  167. AVAsset *secondAsset = [AVURLAsset URLAssetWithURL:_recordAudioUrl options:nil];
  168. CMTimeRange secondTimeRange = CMTimeRangeFromTimeToTime(timeZero, secondAsset.duration);
  169. [composition insertTimeRange:secondTimeRange ofAsset:secondAsset atTime:asset.duration error:nil];
  170. DDLogVerbose(@"join added 2: %f %@", CMTimeGetSeconds(secondAsset.duration), _recordAudioUrl);
  171. AVComposition *immutableSnapshotComposition = [composition copy];
  172. [[NSFileManager defaultManager] removeItemAtURL:_tmpRecorderFile error:nil];
  173. _tmpRecorderFile = [self tmpAudioUrlWithFileNamed:kRecordTmpFileName];
  174. [self saveAudioAsset:immutableSnapshotComposition toURL:_tmpRecorderFile];
  175. } else {
  176. _tmpRecorderFile = [self tmpAudioUrlWithFileNamed:kRecordTmpFileName];
  177. AVAsset *asset = [AVURLAsset URLAssetWithURL:_recordAudioUrl options:nil];
  178. [self saveAudioAsset:asset toURL:_tmpRecorderFile];
  179. }
  180. }
  181. - (void)saveAudioAsset:(AVAsset *)asset toURL:(NSURL *)url {
  182. NSError *error;
  183. if ([[NSFileManager defaultManager] removeItemAtURL:url error:&error] == NO) {
  184. DDLogError(@"audio export could not delete file: %@ error: %@", error, url);
  185. };
  186. AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetMediumQuality];
  187. exportSession.outputURL = url;
  188. exportSession.shouldOptimizeForNetworkUse = YES;
  189. exportSession.outputFileType = AVFileTypeMPEG4;
  190. [exportSession exportAsynchronouslyWithCompletionHandler:^(void) {
  191. DDLogVerbose(@"audio export completed: %ld %@", (long)exportSession.status, url);
  192. if (exportSession.error) {
  193. DDLogError(@"audio export error: %@", exportSession.error);
  194. }
  195. dispatch_semaphore_signal(_sema);
  196. }];
  197. _sema = dispatch_semaphore_create(0);
  198. dispatch_semaphore_wait(_sema, dispatch_time(DISPATCH_TIME_NOW, kMaxSaveWaitTimeS * NSEC_PER_SEC));
  199. }
  200. - (void)joinWithTmpFile {
  201. if (_tmpRecorderFile) {
  202. AVMutableComposition *composition = [AVMutableComposition composition];
  203. AVAsset *asset = [AVURLAsset URLAssetWithURL:_tmpRecorderFile options:nil];
  204. CMTime timeZero = CMTimeMake(0, asset.duration.timescale);
  205. CMTimeRange timeRange = CMTimeRangeFromTimeToTime(timeZero, asset.duration);
  206. [composition insertTimeRange:timeRange ofAsset:asset atTime:timeZero error:nil];
  207. DDLogVerbose(@"join added: %f %@", CMTimeGetSeconds(asset.duration), _tmpRecorderFile);
  208. AVAsset *secondAsset = [AVURLAsset URLAssetWithURL:_recordAudioUrl options:nil];
  209. CMTimeRange secondTimeRange = CMTimeRangeFromTimeToTime(timeZero, secondAsset.duration);
  210. [composition insertTimeRange:secondTimeRange ofAsset:secondAsset atTime:asset.duration error:nil];
  211. DDLogVerbose(@"join added 2: %f %@", CMTimeGetSeconds(secondAsset.duration), _recordAudioUrl);
  212. AVComposition *immutableSnapshotComposition = [composition copy];
  213. [[NSFileManager defaultManager] removeItemAtURL:_tmpRecorderFile error:nil];
  214. _tmpRecorderFile = nil;
  215. _tmpFileDuration = 0;
  216. [self saveAudioAsset:immutableSnapshotComposition toURL:_recordAudioUrl];
  217. }
  218. }
  219. @end