Save Youtube video to iPhone in the app - iphone

Playing Youtube video in the app is easy and well documented around.
There are two problems with that:
after closing Youtube player, if user wants to play it again it has to wait for online streaming again
can't play offline (load video at home to watch on the road)
Does anyone have code to:
download Youtube video to documents folder and show progress of download
play downloaded video by loading file from documents folder (meaning even when not connected to the internet)

To download the video from YouTube:
Get the URL to download from, via the YouTube API or whatever other method.
Create an NSOutputStream or NSFileHandle opened on a temporary file (in NSTemporaryDirectory() or a temp-named file in your Documents directory).
Set up your progress bar and whatever else you need to do.
Allocate and start an NSURLConnection to fetch the file from the URL. Do not use sendSynchronousRequest:returningResponse:error:, of course.
In the connection:didReceiveResponse: delegate method, read out the length of data to be downloaded for proper updating of the progress bar.
In the connection:didReceiveData: delegate method, write the data to the output stream/file handle and update the progress bar as necessary.
In connectionDidFinishLoading: or connection:didFailWithError:, close the output stream/file handle and rename or delete the temporary file as appropriate.
To play it back, just use NSURL's fileURLWithPath: to create a URL pointing to the local file in the Documents directory and play it as you would any remote video.

Ive used classes from this project: https://github.com/larcus94/LBYouTubeView
It works fine for me.
I can download youtube videos.
I used this code:
LBYouTubeExtractor *extractor = [[[LBYouTubeExtractor alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:(#"http://www.youtube.com/watch?v=%#"), self.videoID ]] quality:LBYouTubeVideoQualityLarge] autorelease];
[extractor extractVideoURLWithCompletionBlock:^(NSURL *videoURL, NSError *error) {
if(!error) {
NSLog(#"Did extract video URL using completion block: %#", videoURL);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data = [NSData dataWithContentsOfURL: videoURL];
NSString *pathToDocs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filename = [NSString stringWithFormat:(#"video_%#.mp4"), self.videoID ];
[data writeToFile:[pathTODocs stringByAppendingPathComponent:filename] atomically:YES];
NSLog(#"File %# successfully saved", filename);
});
} else {
NSLog(#"Failed extracting video URL using block due to error:%#", error);
}
}];
You can show progress of downloading using technique described in the posts above.

Here is my example: https://github.com/comonitos/youtube_video
I used PSYouTubeExtractor.h class by Peter Steinberger It can get youtube mp4 video url and than downloading and viewing is not a problem
NSURLConnection
+
NSNotificationCenter
+
PSYouTubeExtractor
+
NSMutableData

check these projects -
https://github.com/iosdeveloper/MyTube
https://github.com/pvinis/mytube
these will definitely help you!!

I don't personally know how to download youtube videos (and the code is too big to put in an answer here).
However, here's a complete youtube downloading example here.
It's an open source youtube downloader called LoadTube: here's the a link to the source code.

I would play the video and figure out where the temp file is being stored. If you can get access to it, copy it into some document folder for offline viewing.

Related

iPhone- Avoid video compression in UIImagePickerController

In my app , im uploading videos to server. Im using the native UIImagePickercontroller to pick the videos from the gallery.
The delegate i have is ;
imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
My application has to work in the background and while picking large videos from gallery the compressing time is so annoyingly high that , the user some how gets irritated and exits the app.While this occur, the beginbackgroundTaskWithExpirationhandler gives me 10 mins for bgTask.But if the compression process is in excess of 10 mins while app is in background the OS suspends /kills my app.
Do you have any idea how I can avoid this.??
Sadly, there is no way to avoid compression completely. Setting the video quality to high should help though.
myController.videoQuality = UIImagePickerControllerQualityTypeHigh;
EDIT: I have not tested this, but it sounds like it would work. It's a remake of the UIImagePickerController that claims to give raw access to images and videos.
GitHub: https://github.com/elc/ELCImagePickerController
More info about it: http://www.icodeblog.com/2010/10/07/cloning-uiimagepickercontroller-using-the-assets-library-framework/
If you know how to acquire a PHAsset object, use this instead of a third-party solution (finer control, never have to upgrade):
[[PHImageManager defaultManager] requestAVAssetForVideo:phAsset options:nil resultHandler:^(AVAsset *avAsset, AVAudioMix *audioMix, NSDictionary *info) {
NSURL *url = (NSURL *)[[(AVURLAsset *)avAsset URL] fileReferenceURL];
NSLog(#"url = %#", [url absoluteString]);
NSLog(#"url = %#", [url relativePath]);
}];
Whereas phAsset is the PHAsset object, and avAsset is the resulting AVAsset object generated by PHImageManager, the output to the console from the above code will produce, for example:
2016-04-16 01:15:40.155 ChromaEpsilon[3423:933358] url = file:///.file/id=16777218.8262005
2016-04-16 01:15:40.155 ChromaEpsilon[3423:933358] url = /private/var/mobile/Media/DCIM/108APPLE/IMG_8421.MOV
There's more than just these two, I believe, but start here.

Play remote mp3 using iOS

I have a remote mp3 (small file, just a few seconds) which I have the URL.
I need to play it on an App that uses iOS 4.
The URL is not exactly a .mp3 file, but it is a dynamic .php url that requests the .mp3 file. If I put that php route in the browser it downloads the mp3 file.
I am trying to use this project (https://github.com/mattgallagher/AudioStreamer) but it isn't working. The audio starts but it only plays a part of it.
How can I do it?
If it's truly just a small (and static, non-streaming) mp3 file, why not consider doing something like:
NSError * error = nil;
AVAudioPlayer * avPlayerObject =
[[AVAudioPlayer alloc] initWithContentsOfURL: yourRemoteURL error:&error];
if(avPlayerObject)
{
[avPlayerObject play];
}
Check out Apple's AVAudioPlayer class (documentation linked for you).

Save MP4 into iPhone photo album

I have an app that plays video clips through the MPMovieplayer. These clips are in mp4 format and everything works dandy. I want to take that same clip and save it into the photo album. This works if I manually sync the video from a computer through iTunes to the phone. It appears to transcode the video file and store it as a .MOV format.
However, when I try and save the video while in the app via code, I get a video format error. So my question is how do I get my video to save in the photo album? If this is not possible with mp4 how do I transcode (in app) to .MOV?
Here is the code:
ALAssetsLibrary* library = [[ALAssetsLibrary alloc]init];
if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:moviePlayerController.contentURL])
{
NSURL *clipURl = moviePlayerController.contentURL;
[library writeVideoAtPathToSavedPhotosAlbum:clipURl completionBlock:^(NSURL *assetURL, NSError *error)
{
if (error)
[ErrorAlertView showError:error];
else [ErrorAlertView showErrorTitle:#"Success" message:#"Your video clip is saved"];
}];
}
[library release];
Is your contentURL a file path URL or a web URL? For the writeVideoAtPathToSavedPhotosAlbum method, in my testing you actually need a file path URL created (for example) in this way:
NSString *pathString = [[NSBundle mainBundle] pathForResource:#"filename" ofType:#"mp4"];
NSString *pathURL = [NSURL fileURLWithPath:pathString isDirectory:NO];
This means you need to first download the movie from the web, if you're using a web URL. I recommend ASIHTTPRequest, using the setDownloadDestinationPath: method to set the download directory.
In general, mp4 files should work if they're the right resolution for the right (retina, non-retina, iPad) device (see my tests of supported video files here).
If the video still gives a NO response on videoAtPathIsCompatibleWithSavedPhotosAlbum: after making absolutely sure the file path URL is correct, then you'll need to use AVAssetExportSession (with AVAssetExportPresetLowQuality, AVAssetExportPresetMediumQuality, or AVAssetExportPresetHighestQuality) to get a device-appropriate file that you can then save to the Photo Album.

Progressive download using Matt Gallagher's audio streamer

I'm a completely n00b when talking about audio. I'm using Matt Gallagher's audio streamer on my radio app. How may I use progressive download? Also, ExtAudioFile is a good idea too :)
Edit:
Used this:
length = CFReadStreamRead(stream, bytes, kAQDefaultBufSize);
if(!data)
data =[[NSMutableData alloc] initWithLength:0];
[data appendData:[NSData dataWithBytes:bytes length:kAQDefaultBufSize]];
Now I can save the audio data using writeToFile:atomically: NSData method, but the audio won't play. Also, if I try to load it on a AVAudioPlayer, I get an error.
I'm trying to do something similar. I ended up doing it like this:
length = CFReadStreamRead(stream, bytes, kAQDefaultBufSize);
// Save data
if (saveLocation){
NSFileHandle *mp3 = [NSFileHandle fileHandleForWritingAtPath:saveLocation];
[mp3 seekToEndOfFile];
[mp3 writeData:[NSData dataWithBytes:bytes length:length]];
[mp3 closeFile];
}
Some problems to be aware of. You should make sure that the file at saveLocation exists. I made a new initializer with the mp3 url and saveLocation path, and put the check there. Also, be aware that if the user performs a seek in the mp3 this will not realize that. Basically, it will record exactly what gets played back. It is not smart enough to realize that the playback position moved. However, if you just start the stream, and allow it to finish the whole mp3 (assuming that it has an end) it should save just fine.

iPhone + file upload control

I have an application which uploads file from iPhone to web server.
Problem is that I want to give users a control like from which they can select the file / photo from the device and which is than uploaded on server.
Can anyone help me
You can get the UIImage content as a JPEG or PNG wrapped in NSData:
NSData *data = UIImageJPEGRepresentation(image, 1);
if( data ) { // it's possible nil may be returned
;// do stuff here.
// see: link to other answer on SO below.
// if you want to write to file, try:
[data writeToFile:filePath atomically:YES];
}
File Upload to HTTP server in iphone programming
I think you want to use an ImagePickerController that is the system component to allow a user to choose a photo.