2016-12-21 1 views
5

신속한 iOS 앱을 제작 중이며 클라이언트가 오디오 녹음 문제를 반환했습니다. 기본적으로 아무 것도 녹음하지 않습니다. 그는 ios 9.x가 설치된 iPhone 5/5에서 테스트를 마쳤습니다. 사용 권한을 확인하고 전화에 충분한 공간이 있는지 여부는 문제가 아닙니다.신속한 오디오 녹음

개인적으로 시뮬레이터에서 ios 10.x 및 iphone 5가있는 iphone 6s 장치로 테스트 한 결과 기록이 작동합니다. 누구든지 전에 이런 일이 생기거나 어쩌면 나는 잘못을 저질렀습니다.

앱이 수행하는 기능에 여러 가지 설명을 추가했습니다.

protocol RecordAndPlayManagerDelegate : class{ 
    func recorderDidStopRecording() 
} 

class RecordAndPlayManager: NSObject, AVAudioRecorderDelegate { 
    var soundRecorder: AVAudioRecorder! 
    let recordSettings = [ 
     AVFormatIDKey: Int(kAudioFormatMPEG4AAC), 
     AVSampleRateKey: 12000, 
     AVNumberOfChannelsKey: 1, 
     AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue 
    ] 
    class func directoryURL() -> URL? { 
     let fileManager = FileManager.default 
     let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask) 
     let documentDirectory = urls[0] as URL 
     let soundURL = documentDirectory.appendingPathComponent("recording.m4a") 
     return soundURL 
    } 

    //calling this from outside to get the audio 
    class func getLocalOrRemoteRecording(_ recordingID : String!) -> URL?{ 

     let fileManager = FileManager.default 
     let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask) 
     let documentDirectory = urls[0] as URL 
     let soundURL = documentDirectory.appendingPathComponent(recordingID) 

     if (fileManager.fileExists(atPath: soundURL.path)){ 
      return soundURL 
     } 

     let path = kBaseServerURLNOPORT + "data/" + recordingID 
     let url = URL(string: path) 

     return url 

    } 

    //called from outside, recordingID -> name of the file 
    class func storeRecording(_ recordingID : String!) -> URL? { 
     let fileManager = FileManager.default 
     let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask) 
     let documentDirectory = urls[0] as URL 
     let soundURL = documentDirectory.appendingPathComponent("recording.m4a") 

     let data = try? Data(contentsOf: soundURL) 
     //data here has only 28bytes and from this I know it didn't record. In my tests, I always get at least 20000 bytes. 

     let newSoundURL = documentDirectory.appendingPathComponent(recordingID) 
     try? data?.write(to: newSoundURL, options: [.atomic]) 

     do { 
      try FileManager.default.removeItem(at: soundURL) 
     } catch _ { 
      print("failed to delete file") 
      return newSoundURL 
     } 

     return newSoundURL 
    } 

    //called on viewDidLoad in another screen 
    func setupRecorder() { 
     let url = DRMessageRecordAndPlayManager.directoryURL()! 
     do { 
      try self.soundRecorder = AVAudioRecorder(url: url, settings: self.recordSettings) 
     } catch _ { 
      return 
     } 
     soundRecorder.delegate = self 
     soundRecorder.prepareToRecord() 
    } 

    //calling this from outside to start recording 
    func startRecording() { 
     if !self.soundRecorder.isRecording { 
      let audioSession = AVAudioSession.sharedInstance() 
      do { 
       try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord) 
       try audioSession.setActive(true) 
       soundRecorder.record(forDuration: 15) 
      } catch { 
      } 
     } 
    } 

    //called from outside when I hit stop 
    func stopRecording() { 

     self.soundRecorder.stop() 
     let audioSession = AVAudioSession.sharedInstance() 

     do { 
      try audioSession.setActive(false) 
     } catch { 
     } 
    } 

    func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { 
     self.delegate?.recorderDidStopRecording() 
    } 
} 
+0

오디오 녹음 최저 자습서 : https://iosdevcenters.blogspot.com/2016/05/audio-recording-and-playing-in-swift-30.html –

답변

5

내 생각 startRecording()에서 catch가 예상대로 작동하고 충돌을 방지하지만, 당신이 그것을 로그인하지 않는 점이다. 여기

catch { 
    // or use an alert controller to display the error 
    print("caught error: \(error)") 
} 
0

목표 C에서 오디오 녹음에 대한 몇 가지 코드는 다음과 같습니다

나는 두 개의 catch 문은 다음과 같이 제공된 오류 개체가 인쇄 변경하는 것이 좋습니다. 스위프트 3.0

NSMutableDictionary *recordSetting; 

NSString *recorderFilePath; 

AVAudioRecorder *recorder; 

- (void) startRecording{ 


    AVAudioSession *audioSession = [AVAudioSession sharedInstance]; 

    NSError *err = nil; 

    [audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err]; 

    if (err) { 

     NSLog(@"audioSession: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]); 

     return; 
    } 

    [audioSession setActive:YES error:&err]; 

    err = nil; 

    if (err) { 

     NSLog(@"audioSession: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]); 

     return; 
    } 

    recordSetting = [[NSMutableDictionary alloc] init]; 

    [recordSetting setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey]; 

    [recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey]; 

    [recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey]; 

    [recordSetting setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey]; 

    [recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey]; 

    [recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey]; 

    // Create a new dated file 
    NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0]; 

    NSString *caldate = [now description]; 

    recorderFilePath = [NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, caldate]; 

    NSURL *url = [NSURL fileURLWithPath:recorderFilePath]; 

    err = nil; 

    recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err]; 

    if (!recorder) { 

     NSLog(@"recorder: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]); 

     return; 
    } 

    //prepare to record 
    [recorder setDelegate:self]; 

    [recorder prepareToRecord]; 

    recorder.meteringEnabled = YES; 

    BOOL audioHWAvailable = audioSession.inputAvailable; 

    if (!audioHWAvailable) { 

     UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"title_warning", nil) message:NSLocalizedString(@"recorder_warning_message", nil) preferredStyle:UIAlertControllerStyleAlert]; 

     UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"ok_action", nil) style:UIAlertActionStyleDefault handler:nil]; 

     [alertController addAction:ok]; 

     [self presentViewController:alertController animated:YES completion:nil]; 

     return; 

    } else { 

     [recorder record]; 
    } 
} 
+0

감사합니다,하지만 문제는 있었다 신속하고 obj-c가 아닙니다. –