AVAudioPlayer play from buffer - iphone

I want to stream audio file from google drive, the only method from google drive sdk from which I can track what is downloaded is [fetcher setReceivedDataBlock:^(NSData *dataReceivedSoFar), so I implemented something like this, but I am not so sure if this is a good solution so I am asking an advice from you guys.
Ok, since I can only get dataReceivedSoFar, I am deleting the already downloaded data from it, and then appending the new data to saved data, and start playing with AVAudioPlayer when the data length is greater than 100 000 bytes.
Please tell me if this is a good solution and if you have some advice regarding it.
Code:
GTMHTTPFetcher *fetcher =
[[self driveService].fetcherService fetcherWithURLString:song.filePath];
NSArray *myPathList = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [myPathList objectAtIndex:0];
NSString *songPath = [[NSString alloc] initWithString: [cachesDir stringByAppendingPathComponent:[NSString stringWithFormat:#"Song.%#", [song.name pathExtension]]]];
[fetcher setReceivedDataBlock:^(NSData *dataReceivedSoFar) {
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
if (![filemgr fileExistsAtPath: songPath ] == YES)
[filemgr createFileAtPath:songPath contents:nil attributes:nil];
NSData *currentData = [NSData dataWithContentsOfFile:songPath];
NSLog(#"LENGTH: %d", currentData.length);
NSMutableData *mutableData = [NSMutableData dataWithData:dataReceivedSoFar];
if (currentData.length > 0) {
[mutableData replaceBytesInRange:NSMakeRange(0, [currentData length]) withBytes:NULL length:0];
}
NSFileHandle *handle = [NSFileHandle fileHandleForUpdatingAtPath:songPath];
[handle seekToEndOfFile];
[handle writeData:mutableData];
//[handle synchronizeFile];
[handle closeFile];
if (!self.audioPlayer.playing && dataReceivedSoFar.length > 100000)
{
NSURL *URL = [NSURL fileURLWithPath:songPath];
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:URL error:nil];
[self.audioPlayer play];
NSLog(#"Audio player started playing");
}

Related

When we open pdf in iPhone then how to save this pdf in iphone

I am very new to iOS. I create PDF and load this PDF on UIWebView
now this time I want to save or download this PDF in iPhone when we tapped download button then all exits PDF supporter show like as open ibook ,open in chrome. This type of option show but when we tap any one then my application closed.
-(void)show_Button
{
NSArray *docDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [docDirectories objectAtIndex:0];
NSString *filePAth = [docDirectory stringByAppendingPathComponent:#"myPDF.pdf"];
NSLog(#"filePath = %#", filePAth);
NSURL *url2 = [NSURL fileURLWithPath:filePAth];
NSLog(#"url2 = %#", url2);
UIDocumentInteractionController *docContr = [UIDocumentInteractionController
interactionControllerWithURL:url2];
docContr.delegate=self;
[docContr presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
}
so how to save or download this pdf in Iphone please solve this problem....
I believe you can simple use the belo two line:
NSData *myFile = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"your_url"]];
[myFile writeToFile:[NSString stringWithFormat:#"%#/%#", [[NSBundle mainBundle] resourcePath], #"yourfilename.pdf"] atomically:YES];
I hope this it will help you,
Saving the pdf into app
NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: path]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"pdfname.pdf"];
NSError *writeError = nil;
[imageData writeToFile:filePath options:NSDataWritingAtomic error:&writeError];
if (writeError) {
NSLog(#"Error writing file: %#", writeError); }
Getting the pdf from the NSDocument Directory
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:&error];
for(int i=0;i<[filePathsArray count];i++)
{
NSString *strFilePath = [filePathsArray objectAtIndex:i];
if ([[strFilePath pathExtension] isEqualToString:#"pdf"])
{
NSString *pdfPath = [[stringPath stringByAppendingFormat:#"/"] stringByAppendingFormat:strFilePath];
NSData *data = [NSData dataWithContentsOfFile:pdfPath];
if(data)
{
UIImage *image = [UIImage imageWithData:data];
[arrayOfImages addObject:image];
}
}
}

How to use ogg.framwork in xcode to play audio from url or data

From couple of days I was searching of how to play ogg on iPhone. But not successful. I found this post which points towards precompiled-ogg-vorbis-libraries-for-ios, but I don't know how to use this framework or libraries. I am new in coding. I also found this post
but it plays ogg audio from bundle. I want to play from a given url, like wikipedia audios. any help will be great. Thanks
UPDATE:
I found another library or file which can be use in iOS but, still I don't know how to use in Xcode. Ogg Vorbis I audio decoder by Sean Barrett. Any idea how to use this.
UPDATE 2:
Just tried to use it something like this, but output file have no sound. Any idea where I am going wrong.
NSString *file = #"http://upload.wikimedia.org/wikipedia/commons/b/b2/En-us-Pakistan.ogg";
NSURL *fileURL = [NSURL URLWithString:file];
NSData * data = [NSData dataWithContentsOfURL:fileURL];
unsigned char* array = (unsigned char*) [data bytes];
int len = [data length];
if (data != nil) {
NSLog(#"\nis not nil");
//NSString *readdata = [[NSString alloc] initWithContentsOfURL:(NSData *)data ];
stb_vorbis* Stream = stb_vorbis_open_memory(array, len, NULL, NULL);
if (Stream)
{
stb_vorbis_close(Stream);
//return true;
}
else
{
//return false;
}
}
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);
NSData *ddata = [NSData dataWithBytes:byteData length:len];
if (ddata == nil) {
NSLog(#"data nil");
}
else{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"wikiaudio"];
NSError *error;
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder if it doesn't already exist
NSString * filename = [#"hello" stringByAppendingString:#".mp3"];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", dataPath,filename];
[ddata writeToFile:filePath atomically:YES];
NSLog(#"filepath %#", filePath);
}

getting too much memory allocation with no leaks, app crashes more likely on ipad

I have this code of getting two video frames each of two different video. I am merging them into single frame and then creating a movie with merged frames. But the problem is app crashes due to memory warning. Here is my code:
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"/Documents/movie.mp4"]];
NSURL *outputURL = [NSURL fileURLWithPath:filePath];
player = [[MPMoviePlayerController alloc]initWithContentURL:outputURL];
float frame = 0.00;
int count = 10;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
docPath = [docPath stringByAppendingPathComponent:#"OutPut"];
BOOL success = [fileManager fileExistsAtPath:docPath];
if (success) {
[fileManager removeItemAtPath:docPath error:nil];
}
[fileManager createDirectoryAtPath:docPath withIntermediateDirectories:YES attributes:nil error:nil];
for (frame = (frameStartTime); frame < (frameStartTime+5); frame+=0.033) {
UIImage * singleFrameImage = [player thumbnailImageAtTime:frame timeOption:MPMovieTimeOptionExact];
[player pause];
NSString *imageName = [NSString stringWithFormat:#"export2%d.png",count];
NSString * file = [[NSBundle mainBundle]pathForResource:imageName ofType:nil];
UIImage *overlayImage = [UIImage imageWithData:[NSData dataWithContentsOfFile:file]];
count = count + 1;
NSString *imagePath = [NSString stringWithFormat:#"%#/%#", docPath, imageName];
if (overlayImage) {
UIImage * outImage = [self mergeImage:singleFrameImage withImage:overlayImage];
NSData *imgData = [[NSData alloc] initWithData:UIImagePNGRepresentation(outImage)];
[fileManager createFileAtPath:imagePath contents:imgData attributes:nil];
[imgData release];
}
else {
NSData *imgData = UIImagePNGRepresentation(singleFrameImage);
[fileManager createFileAtPath:imagePath contents:imgData attributes:nil];
}
[outputFramesArray addObject:imagePath];
}
[player release];
if([fileManager fileExistsAtPath:filePath]) {
[fileManager removeItemAtPath:filePath error:nil];
}
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"/Documents/movie1.mp4"]];
NSLog(#"filePath %#", path);
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
}
[self writeImageAsMovie:outputFramesArray toPath:path size:CGSizeMake(480, 320) duration:10];
NSLog(#"hello Your layering is completed");
[outputFramesArray removeAllObjects];
[outputFramesArray release];
The allocation in instrument is maximum in this line (90%):
NSData *imgData = [[NSData alloc] initWithData:UIImagePNGRepresentation(outImage)];
In my whole app, the allocation level rise at only this point of code reaches to 130MB.
Could any of you suggest any solution?
It's most like because you are consuming memory within your loop and the allocated memory in the current stack gets too big before you return to the main loop where things get deallocated.
Read this blog post for more details.
Do this:
...
for (frame = (frameStartTime); frame < (frameStartTime+5); frame+=0.033)
{
#autoreleasepool {
// Do whatever you do in your for loop...
}
}
...
It will create a local pool that gets drained at each iteration.

MPMoviePlayerController doesn't play newly saved video file

I'm using an imagePickerController to record video. In the imagePickerController:didFinishPickingMediaWithInfo: function I'm trying to set the video to a previously defined MPMoviePlayerController:
if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]){
NSURL *movieUrl = [info objectForKey:UIImagePickerControllerMediaURL];
[self.moviePlayer setContentURL:movieUrl]];
}
This is working fine and the video is indeed playing.
But I want to save the file for later use. When I do this and use the saved file for the moviePlayer, nothing happens:
I've tried this (saving the data to a new file)
NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *newPath = [directory stringByAppendingPathComponent:#"myMovie.mov"];
NSData *videoData = [NSData dataWithContentsOfURL:movieUrl];
[videoData writeToFile:newPath atomically:NO];
[self.moviePlayer setContentURL:[NSURL URLWithString:newPath]];
or this (copying the temp video file to my document folder)
NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *newPath = [directory stringByAppendingPathComponent:#"myMovie.mov"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
[fileManager copyItemAtPath:[videoUrl path] toPath:newPath error:&error];
[self.moviePlayer setContentURL:[NSURL URLWithString:newPath]];
Without any success, even though the file at newPath does exist... What am I doing wrong?
Ok I finally found the issue. The problem was not in fact with the MPMoviePlayerController but with the line:
[self.moviePlayer setContentURL:[NSURL URLWithString:newPath]];
I fixed it by replacing that line with:
[self.moviePlayer setContentURL:[NSURL fileURLWithPath:newPath isDirectory:NO]];
Hope that will help someone else!
use the code below:
NSData *movieData;
NSError *dataReadingError = nil;
movieData = [NSData dataWithContentsOfURL: movieURL options:NSDataReadingMapped error:&dataReadingError];
if(movieData != nil)
NSLog(#"Successfully loaded the data.");
else
NSLog(#"Failed to load the data with error = %#", dataReadingError);

UIWebView displays locally stored document on simulator but not device

I have an issue where I'm trying to view a document (Word document, image, or video) that I have stored locally. I'm using UIWebView and on the Simulator it works perfectly, but on the device, it's a blank screen (no errors thrown in console). Here's my code to view the document:
UIWebView *newWebView;
if (appDelegate.IS_IPAD)
{
newWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 768, 1024)];
}
else
{
newWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
}
newWebView.scalesPageToFit = YES;
[self setWebView: newWebView];
[newWebView release], newWebView = nil;
[[self webView] setDelegate: self];
[[self view] addSubview:[self webView]];
NSURL *nsURL = [NSURL fileURLWithPath:filePath isDirectory:NO];
[[self webView] loadRequest:[NSURLRequest requestWithURL:nsURL]];
Here's how I'm saving the document locally before viewing. I do think the file is getting successfully saved on the device as it does on the simulator.
// Save the file on the device
NSURL *contentUrl = [NSURL URLWithString:selectedContent.contentUrl];
NSString *fileName = [[contentUrl absoluteString] lastPathComponent];
NSString *homeDirectoryPath = NSHomeDirectory(); // Create the path
NSString *unexpandedPath = [homeDirectoryPath stringByAppendingString:#"/MyApp/"];
NSString *folderPath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedPath stringByExpandingTildeInPath]], nil]];
NSString *unexpandedImagePath = [folderPath stringByAppendingFormat:#"/%#", fileName];
NSString *filePath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedImagePath stringByExpandingTildeInPath]], nil]];
if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath isDirectory:NULL])
{
[[NSFileManager defaultManager] createDirectoryAtPath:nil withIntermediateDirectories:NO attributes:nil error:nil];
}
// Do the actual write of the file to the device
NSData *fileData = [NSData dataWithContentsOfURL:myUrl]; // Create the file data reference
[fileData writeToFile:filePath atomically:YES]; //Save the document to the home directory
Watch out for case issues. The simulator is not case sensitive whereas the iPhone is!
I solved this by saving my document to the default Documents Directory. Here's the code I used to accomplish this:
NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [arrayPaths objectAtIndex:0];
NSString *filePath = [docDirectory stringByAppendingString:#"/"];
filePath = [filePath stringByAppendingString:fileName];
NSData *fileData = [NSData dataWithContentsOfURL:myUrl];
[fileData writeToFile:filePath atomically:YES];