objective-cwatchkitwatchos-2audio-player

presentMediaPlayerControllerWithURL dismissing immediately without playing the audio


I'm creating a watch application which records an audio and play that audio. The recorded audio is saved in the Apps Groups and I used the following code for playing the audio.

- (void)playAudio
{
    // Playing the audio from the url using the default controller
    [self presentMediaPlayerControllerWithURL:self.audioFileURL options:@{WKMediaPlayerControllerOptionsAutoplayKey : @YES} completion:^(BOOL didPlayToEnd, NSTimeInterval endTime, NSError * _Nullable error) {
        NSLog(@"Error = %@",error);
    }];
}

Unfortunately I am getting the following error and the player controller get dismissed immediately.

Error Domain=com.apple.watchkit.errors Code=4 "The operation could not be completed" UserInfo={NSLocalizedFailureReason=An unknown error occurred (1), NSUnderlyingError=0x16daa810 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}, NSLocalizedDescription=The operation could not be completed}.

Then I downloaded a sample project (WatchKitAudioRecorder Sample code) from Apple WatchOS Developer library but they are also having the same issue. I don't know why this is not working even in Apple Sample code :(


Solution

  • Finally I found that the data is not writing to the url path. Also should be written in the following path: Library/Caches/filename.extension Here is a sample code, which may help someone.

    - (void)writeAudioToAppGroupsWithData:(NSData *)audioData
    {
        // Writing the audio data to the App Groups
        NSURL *containerURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:APP_GROUP_IDENTIFIER];
        containerURL = [containerURL URLByAppendingPathComponent:[NSString stringWithFormat:DIRECTORY_PATH]];
        [audioData writeToURL:containerURL atomically:YES];
    }
    

    In this case make sure that your DIRECTORY_PATH is Library/Caches/filename.extension. Eg: Library/Caches/Audio.mp3