session:didReceiveFile: Not Playing Audio File (iPhone to Watch) [duplicate] - ios

This question already has an answer here:
How to send data from Iphone to Apple Watch in OS2 in Objective-C
(1 answer)
Closed 7 years ago.
I am having an issue with getting an audio file that I record on my iPhone to play out of my Watch speakers.
Here is the code I have for sending from iPhone to Watch.
- (void)sendLiveAudioRecordingToWatch
{
NSError *error;
NSFileManager *files = [NSFileManager defaultManager];
NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *record = [docs stringByAppendingPathComponent: #"LiveAudio.m4a"];
NSURL *URL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier: #"group.myCompany.myApp"];
NSURL *outputURL = [URL URLByAppendingPathComponent: #"PhoneToWatch.mp4"];
NSString *path = [NSString stringWithFormat: #"%#", outputURL];
NSLog(#"%#", [NSURL fileURLWithPath: path]);
[files removeItemAtPath: [outputURL path] error: &error];
BOOL fileExists = [files isReadableFileAtPath: record];
if (fileExists)
{
NSLog(#"Live Audio Recording Saved!");
[files copyItemAtPath: record toPath: [outputURL path] error: &error];
if (!error)
{
NSLog(#"Temporary Recording Copied To Group");
BOOL deleteRecord = [files removeItemAtPath: record error: &error];
if (deleteRecord)
{
NSLog(#"Temporary Recording Removed");
if ([WCSession isSupported])
{
WCSession *session = [WCSession defaultSession];
NSLog(#"WCSession isSupported");
[session setDelegate: self];
[session activateSession];
if ([session isReachable])
{
NSLog(#"File Is Being Transferred");
[[WCSession defaultSession] transferFile: outputURL metadata: nil];
}
else
{
NSLog(#"Watch Not Reachable");
}
}
}
else
{
NSLog(#"Failed To Delete Temorary File");
}
}
else
{
NSLog(#"Error Copying Live Audio To Group");
}
}
else
{
NSLog(#"Error Locating Temporary Audio Location");
}
}
Here is the code I have for receiving on Watch from iPhone.
- (void)session: (WCSession *)session didReceiveFile: (WCSessionFile *)file
{
WKAudioFileAsset *asset = [WKAudioFileAsset assetWithURL: [file fileURL]];
WKAudioFilePlayerItem *playerItem = [WKAudioFilePlayerItem playerItemWithAsset: asset];
WKAudioFilePlayer *player = [WKAudioFilePlayer playerWithPlayerItem: playerItem];
[player play];
}
iOS 9.2 watchOS 2.0
Has anyone experienced this, or was able to get this working?

I got this working. WKAudioFilePlayer is used for playing through a bluetooth device, not the speakers of the Apple Watch. In WatchOS 2.0 and higher, you can use:
[self presentMediaPlayerControllerWithURL:url options:options completion:^(BOOL didPlayToEnd, NSTimeInterval endTime, NSError * __nullable error){}];

Related

iOS:How to know which file takes much size-in-application in objective c?

I have third party project which uses following code this code is not all but it write big file(say recording) in app bundle how to find that file?
NSError *audioSessionError = nil;
AVAudioSession *audioSession= [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&audioSessionError];
[audioSession setMode:AVAudioSessionModeDefault error:&audioSessionError];
[audioSession setPreferredSampleRate:16000.0f error:&audioSessionError];
[audioSession setPreferredInputNumberOfChannels:1 error:&audioSessionError];
[audioSession setActive:TRUE error:&audioSessionError];
_sampleRate= [audioSession sampleRate];
// make a capture session that uses the audio session
_captureSession = [[AVCaptureSession alloc]init];
_captureSession.sessionPreset = AVCaptureSessionPreset640x480;
_captureSession.automaticallyConfiguresApplicationAudioSession= NO;
_startTimeMS = [[NSDate date] timeIntervalSince1970] * 1000;
dispatch_queue_t videoQueue = dispatch_queue_create("smmaProcessingQueueVideo", NULL);
[_videoOutput setSampleBufferDelegate:self queue:videoQueue];
dispatch_queue_t audioQueue = dispatch_queue_create("smmaProcessingQueueAudio", NULL);
[_audioOutput setSampleBufferDelegate:self queue:audioQueue];
Same code for video, as well Now, this code write too big file(up to 2 GB) in app. Audio+Video,
I want to find & Delete that file.i tried
NSString *appFolderPath = [[NSBundle mainBundle] resourcePath];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSLog(#"App Directory is: %#", appFolderPath);
NSLog(#"Directory Contents:\n%#", [fileManager directoryContentsAtPath: appFolderPath]);
how to do that? any help will much appreciated.
You can clear temp directory by,
NSArray* tmpDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:NULL];
for (NSString *file in tmpDirectory) {
BOOL suc = [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:#"%#%#", NSTemporaryDirectory(), file] error:NULL];
if (suc) {
NSLog(#"done");
}
NSLog(#"file : %#%#",NSTemporaryDirectory(), file);
}
You can clear cachedirectory like,
dirPaths = NSSearchPathForDirectoriesInDomains(
NSCachesDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSFileManager *manager1 = [NSFileManager defaultManager];
NSArray *filesArDirectory1 = [manager contentsOfDirectoryAtPath:docsDir error:nil];
NSError *err1;
for (NSString *file2 in filesArDirectory1) {
BOOL success = [manager1 removeItemAtPath:[NSString stringWithFormat:#"%#%#", docsDir,file2] error:&err1];
if (!success || err1) {
NSLog(#"error description : %#",[err1 localizedDescription]);
NSLog(#"failed2");
}
else{
NSLog(#"Success2");
}
NSLog(#"files : %#",file2);
}
Try to clear both this directory if it stores data. Check that your document directory stores big data then you need to manage that also.
Hope this will help :)

fail to load iWork file url in documentPicker:didPickDocumentAtURL:

I'm working on an iOS app which can import cloud files using DocumnetPicker, Under Xcode6.1, iphone5s(IOS8.1.1). It's strange that url of .number/.key file could not be load successfully, but others like .pdf/.jpg are fine.
My UTIS:
+ (NSArray*) supportedDocumentTypes
{
return #[(__bridge NSString*) kUTTypeContent,
#"com.apple.iwork.pages.pages",
#"com.apple.iwork.numbers.numbers",
#"com.apple.iwork.keynote.key"];
}
documentPicker:didPickDocumentAtURL: is defined the same in newbox sample:
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
BOOL startAccessingWorked = [url startAccessingSecurityScopedResource];
NSURL *ubiquityURL = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
NSLog(#"ubiquityURL %#",ubiquityURL);
NSLog(#"start %d",startAccessingWorked);
NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
NSError *error;
[fileCoordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
NSData *data = [NSData dataWithContentsOfURL:newURL];
NSLog(#"error %#",error);
NSLog(#"data %#",data);
}];
[url stopAccessingSecurityScopedResource];
}
I believe those are directories (containers) technically, which is why .pdf works but not the .numbers, etc.

Convert a you tube downloaded video to MOV format in iOS

I'm developing an iOS app, which needs to convert a video downloaded using you tube APIs into .mov format. I've tried using AVExportSession output file type set to .mov.`
NSURL * mediaURL = [NSURL fileURLWithPath:outputURL];
AVAsset *video = [AVAsset assetWithURL:mediaURL];
AVAssetExportSession *exportSession = [AVAssetExportSession exportSessionWithAsset:video presetName:AVAssetExportPreset1920x1080];
exportSession.shouldOptimizeForNetworkUse = YES;
exportSession.outputFileType = AVFileTypeQuickTimeMovie;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
documentsPath=[documentsPath stringByAppendingString:#"/Youtube"];
BOOL isDir;
if (![[NSFileManager defaultManager] fileExistsAtPath:documentsPath isDirectory:&isDir]) {
NSError *createDirError;
if (![[NSFileManager defaultManager] createDirectoryAtPath:documentsPath withIntermediateDirectories:YES attributes:nil error:&createDirError]) {
if (createDirError) {
NSLog(#"eror while creating dir == %#", createDirError);
}
}
}
documentsPath = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%d.mov",arc4random()%10000]];
exportSession.outputURL = [NSURL fileURLWithPath:documentsPath];
[exportSession exportAsynchronouslyWithCompletionHandler:^{
switch (exportSession.status) {
case AVAssetExportSessionStatusCompleted:
{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:[NSURL fileURLWithPath:outputURL] completionBlock:^(NSURL *assetURL, NSError *error) {
if (error) {
NSLog(#"error>%#",error.description);
}
else{
if([[NSFileManager defaultManager] fileExistsAtPath:outputURL])
{
[[NSFileManager defaultManager]removeItemAtPath:outputURL error:nil];
}
NSLog(#"asseturl>%#",assetURL);
[[NSFileManager defaultManager] removeItemAtPath:outputURL error:nil];
[self addAssetURL:assetURL toAlbum:#"Fame" withCompletionBlock:^(NSError *error) {
if(error)
{
NSLog(#"Error in saving to Fame album : %#",error.description);
return;
}
}];
}
}];
}
break;
case AVAssetExportSessionStatusFailed:
NSLog(#"Error : %#",exportSession.error.description);
default:
break;
}
NSLog(#"done processing video!");
}];
`
This code saves the video to gallery, but when I fetch the video using asset library, I get mp4 in the url.

AVAudioPlayer successfully calls play method but not playing sound

AVAudioPlayer successfully calls play method and is working properly in the simulator but it is not playing sound. The device has iOS 7.1.1. This is the code that I have used.
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath = [mainBundle pathForResource:#"miata-hn" ofType:#"wav"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSError *error = nil;
/* Start the audio player */
self.playerAudio = [[AVAudioPlayer alloc] initWithData:fileData error:&error];
self.playerAudio.volume = 1;
if (error)
{
NSLog(#"error localized description %#",[error localizedDescription]);
}
if (self.playerAudio != nil)
{
/* Set the delegate and start playing */
self.playerAudio.delegate = self;
if ([self.playerAudio prepareToPlay] && [self.playerAudio play])
{
NSLog(#"player success");
}
else
{
NSLog(#"sound player failed to play audio");
}
}
else
{
/* Failed to instantiate AVAudioPlayer */
}
I got The solution. After adding this line of code the audio is audible in app.
AVAudioSession should be activated.
**
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
[[AVAudioSession sharedInstance] setActive:YES error:&error];
**
Try using:
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];

AVAudioPlayer initWithURL not working to stream radio

I'm trying to stream an radio in my app.
I'm using AVAudioPlayer, but I have an error I don't understand :
NSString *urlString = #"http://broadcast.infomaniak.net/radionova-high.mp3";
NSURL *myURL = [NSURL URLWithString:urlString];
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:myURL error:&error];
if (self.audioPlayer == nil){
NSLog(#"Error loading clip: %#", [error localizedDescription]);
}
else {
self.audioPlayer.delegate = self;
self.audioPlayer.volume = 0.5;
[self.audioPlayer play];
}
And I have the following error :
Error loading clip: The operation couldn’t be completed. (OSStatus error -43.)
Does anyone see what's wrong ?
EDIT :
This is what the Apple docs say:
The AVAudioPlayer class does not provide support for streaming audio
based on HTTP URL's. The URL used with initWithContentsOfURL: must be
a File URL (file://). That is, a local path.
Now what ? :(
download file to document directoty then play file
NSString *urlString = #"http://broadcast.infomaniak.net/radionova-high.mp3";
NSURL *myURL = [NSURL URLWithString:urlString];
NSData *audioData = [NSData dataWithContentsOfURL:myURL];
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#.mp3", docDirPath , fileName];
[audioData writeToFile:filePath atomically:YES];
NSError *error;
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
if (self.audioPlayer == nil) {
NSLog(#"AudioPlayer did not load properly: %#", [error description]);
} else {
self.audioPlayer.delegate = self;
self.audioPlayer.volume = 0.5;
[self.audioPlayer play];
}

Resources