How to record audio and play it with WatchOS2?

767 views Asked by At

In watchOS 2, Apple has included a new feature to allow apps to record short audio files but, how can I call this new method in my existing WatchKit project?

- (void)presentAudioRecordingControllerWithOutputURL:(NSURL * nonnull)URL
                                              preset:(WKAudioRecordingPreset)preset
                                     maximumDuration:(NSTimeInterval)maximumDuration
                                         actionTitle:(NSString * nullable)actionTitle
                                          completion:(void (^ nonnull)(BOOL didSave,
                                                               NSError * nullable error))completion;

My problem is not how to called that method, is that Xcode compiler says that this function is not found. Do I have to include any additional Framework? Could it be because my WatchKit project was create with a previous version of WatchOS?

Thanks!

1

There are 1 answers

2
shu223 On

1) You need to create a file URL at which to store the recorded output.

NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask,YES);
NSString *path = [[filePaths firstObject] stringByAppendingPathComponent:@"rec.m4a"];
NSURL *fileUrl = [NSURL fileURLWithPath:path];

You may specify the extensions .wav, .mp4, and .m4a.

2) Call the method as follows:

[self presentAudioRecordingControllerWithOutputURL:fileUrl
                                            preset:WKAudioRecordingPresetWideBandSpeech
                                   maximumDuration:5.0
                                       actionTitle:@"Some Title"
                                        completion:^(BOOL didSave, NSError * __nullable error) {

                                            NSLog(@"didSave:%d, error:%@", didSave, error);
                                        }];

You can choose preset in addition to the above

  • WKAudioRecordingPresetNarrowBandSpeech
  • WKAudioRecordingPresetHighQualityAudio

In Swift:

self.presentAudioRecordingControllerWithOutputURL(
    self.recFileURL(),
    preset: WKAudioRecordingPreset.WideBandSpeech,
    maximumDuration: 5.0,
    actionTitle: "SomeTitle") { (didSave, error) -> Void in

        print("didSave:\(didSave), error:\(error)")
}

You can play the recorded file as follows:

self.presentMediaPlayerControllerWithURL(
    fileURL,
    options: nil) { (didPlayToEnd, endTime, error) -> Void in

        print("didPlayToEnd:\(didPlayToEnd), endTime:\(endTime), error:\(error)")
}

You can check the detail specification here.