I am using following code to upload .mov file to youtube. It upload successfully but the video don't have any audio. Please tell me if I am doing something wrong....
- (void)uploadVideoFile {
NSString *devKey = #"AI39si4w9QSgQj1JzNxzuiHhFbTm2iLt3mRerGh0UNvlryRPGgQhgIaJA8l95j4YwdC1jBIz6_JaX8eJm2GMgE06FtvIu7E9Sg";
GDataServiceGoogleYouTube *service = [self youTubeService];
[service setYouTubeDeveloperKey:devKey];
NSString *username = txtYName.text;
NSURL *url = [GDataServiceGoogleYouTube youTubeUploadURLForUserID:username];
// load the file data
NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"Documents/movie.mov"]] retain];
NSData *data = [NSData dataWithContentsOfFile:path];
NSString *filename = [path lastPathComponent];
// gather all the metadata needed for the mediaGroup
NSString *titleStr = txtName.text;
GDataMediaTitle *title = [GDataMediaTitle textConstructWithString:titleStr];
NSString *categoryStr = #"Comedy";
GDataMediaCategory *category = [GDataMediaCategory mediaCategoryWithString:categoryStr];
[category setScheme:kGDataSchemeYouTubeCategory];
NSString *descStr = #"this is just test";
GDataMediaDescription *desc = [GDataMediaDescription textConstructWithString:descStr];
NSString *keywordsStr = #"SuperShredBros";
GDataMediaKeywords *keywords = [GDataMediaKeywords keywordsWithString:keywordsStr];
BOOL isPrivate = NO;
GDataYouTubeMediaGroup *mediaGroup = [GDataYouTubeMediaGroup mediaGroup];
[mediaGroup setMediaTitle:title];
[mediaGroup setMediaDescription:desc];
[mediaGroup addMediaCategory:category];
[mediaGroup setMediaKeywords:keywords];
[mediaGroup setIsPrivate:isPrivate];
NSString *mimeType = [GDataUtilities MIMETypeForFileAtPath:path
defaultMIMEType:#"video/quicktime"];
// create the upload entry with the mediaGroup and the file data
GDataEntryYouTubeUpload *entry;
entry = [GDataEntryYouTubeUpload uploadEntryWithMediaGroup:mediaGroup
data:data
MIMEType:mimeType
slug:filename];
SEL progressSel = #selector(ticket:hasDeliveredByteCount:ofTotalByteCount:);
[service setServiceUploadProgressSelector:progressSel];
GDataServiceTicket *ticket;
ticket = [service fetchEntryByInsertingEntry:entry
forFeedURL:url
delegate:self
didFinishSelector:#selector(uploadTicket:finishedWithEntry:error:)];
[self setUploadTicket:ticket];
// [self updateUI];
}
please help me. Thanks in advance.
I think you need to change mime type as below
NSString *mimeType = [GDataUtilities MIMETypeForFileAtPath:fetchPath
defaultMIMEType:#"video/mp4"];
This thing works fine for me and also one more thing i am uploading .Mov file to not only .mp4 or .m4a or .flv
Following should help you:
GDataYouTubeMediaGroup *mediaGroup = [GDataYouTubeMediaGroup mediaGroup];
[mediaGroup setMediaTitle:title];
[mediaGroup setMediaDescription:desc];
[mediaGroup addMediaCategory:category];
[mediaGroup setMediaKeywords:keywords];
[mediaGroup setIsPrivate:NO];
NSString *mimeType = [GDataUtilities MIMETypeForFileAtPath:outputURL.relativePath defaultMIMEType:#"video/quicktime"];
GDataEntryYouTubeUpload *entry;
entry = [GDataEntryYouTubeUpload uploadEntryWithMediaGroup:mediaGroup data:data MIMEType:mimeType slug:filename];
SEL progressSel = #selector(ticket:hasDeliveredByteCount:ofTotalByteCount:);
[service setServiceUploadProgressSelector:progressSel];
GDataServiceTicket *ticket;
ticket = [service fetchEntryByInsertingEntry:entry forFeedURL:url delegate:self didFinishSelector:#selector(uploadTicket:finishedWithEntry:error:)];
for reference: Youtube Upload Quality
change your output audio setting.... it should be like this.....
audioOutputSettings = [NSDictionary dictionaryWithObjectsAndKeys:
[ NSNumber numberWithInt: kAudioFormatMPEG4AAC ], AVFormatIDKey,
[ NSNumber numberWithInt: 1 ], AVNumberOfChannelsKey,
[ NSNumber numberWithFloat: 44100.0 ], AVSampleRateKey,
[ NSNumber numberWithInt: 64000 ], AVEncoderBitRateKey,
[ NSData dataWithBytes: &acl length: sizeof( acl ) ], AVChannelLayoutKey,
nil];
i think Youtube supports flv and mp4 format video files. so please change mimetype.
Hope you get expected results.
Related
I have developed an app that loads a user's videos and when they click on the cell in the tableview it goes to another viewcontroller that holds a bunch of different information.
I'm trying to extract the actual YouTube link from a specific video. I print out the links I get and they come in this form.
https://www.youtube.com/v/Xf5pXlZJr1U?version=3&f=user_uploads&app=youtube_gdata
But I want it to be in this form.
http://www.youtube.com/watch?v=Xf5pXlZJr1U
Reason being that I want people to share the link via social media, but it comes out weird when it's in the first format.
Is there any way to easily convert the links?
SAMPLE CODE AND ANSWER EDIT
GDataEntryBase *entry2 = [[feed entries] objectAtIndex:indexPath.row];
NSString *title = [[entry2 title] stringValue];
NSArray *contents = [[(GDataEntryYouTubeVideo *)entry2 mediaGroup] mediaContents];
GDataMediaContent *flashContent = [GDataUtilities firstObjectFromArray:contents withValue:#"application/x-shockwave-flash" forKeyPath:#"type"];
NSString *tempURL = [flashContent URLString];
NSArray *thumbnails = [[(GDataEntryYouTubeVideo *)entry2 mediaGroup] mediaThumbnails];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[thumbnails objectAtIndex:0] URLString]]];
UIImage *image = [UIImage imageWithData:data];
GDataYouTubeMediaGroup *mediaGroup = [(GDataEntryYouTubeVideo *)entry2 mediaGroup];
GDataMediaDescription *desc2 = [mediaGroup mediaDescription];
NSString *mystring = [desc2 stringValue];
NSArray *listItems = [tempURL componentsSeparatedByString:#"/"];
NSString *NewURL = #"";
NewURL = [NewURL stringByAppendingString:[listItems objectAtIndex:0]];
NewURL = [NewURL stringByAppendingString:#"//"];
NewURL = [NewURL stringByAppendingString:[listItems objectAtIndex:2]];
NewURL = [NewURL stringByAppendingString:#"/"];
NewURL = [NewURL stringByAppendingString:#"watch"];
NewURL = [NewURL stringByAppendingString:#"?v="];
NSArray *listItems2 = [[listItems objectAtIndex:4] componentsSeparatedByString:#"?"];
NewURL = [NewURL stringByAppendingString:[listItems2 objectAtIndex:0]];
If you take a look at NSString docs then you will find number of useful methods for yourself to use, e.g componentsSeparatedByString splitting the string in two different chunks depending on some particular character & stringByAppendingString for appending string to an existing string. It is not difficult to use these methods, just use according to your needs.
I have tried following code :
These is my delegate method of MPMediPickerController :
- (void) mediaPicker: (MPMediaPickerController *) mediaPicker didPickMediaItems: (MPMediaItemCollection *) mediaItemCollection {
// Dismiss the media item picker.
[self dismissModalViewControllerAnimated: YES];
NSLog(#"%# %d",mediaItemCollection,mediaItemCollection.count);
NSArray *newMediaItem= [mediaItemCollection items];
MPMediaItem *item=[[newMediaItem objectAtIndex:0] retain];
[self uploadMusicFile:item];
}
This is my custom method MPMediaItem to NSData:
- (void) uploadMusicFile:(MPMediaItem *)song
{
NSURL *url = [song valueForProperty: MPMediaItemPropertyAssetURL];
AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL: url options:nil];
AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset: songAsset
presetName: AVAssetExportPresetPassthrough];
exporter.outputFileType = #"public.mpeg-4";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *exportFile = [documentsDirectory stringByAppendingPathComponent:
#"exported.mp4"];
NSURL *exportURL = [[NSURL fileURLWithPath:exportFile] retain];
exporter.outputURL = exportURL;
[exporter exportAsynchronouslyWithCompletionHandler:
^{
NSData *data = [NSData dataWithContentsOfFile: [documentsDirectory
stringByAppendingPathComponent: #"exported.mp4"]];
NSLog(#"%#",data);
}];
}
I am getting "null" in NSlog.
I have also check this post :
how to convert nsdata to MPMediaitem song iOS Sdk
but not getting solution.
I am using xcode 4.6 and ios 6.1.
Can any one tell me what is wrong here?
I'm trying to post video to youtube from inside of my iPhone application using the GData API. Here is the code I'm using:
GDataServiceGoogleYouTube* service = [self youTubeService];
[service setYouTubeDeveloperKey:youtubeAppKey];
NSString *username = service.username;
NSURL *url = [GDataServiceGoogleYouTube youTubeUploadURLForUserID:username];
NSData *data = [NSData dataWithContentsOfFile:self.videoPath];
NSString *filename = #"My Cool Video";
NSString *titleStr = #"Title";
GDataMediaTitle *mediaTitle = [GDataMediaTitle textConstructWithString:titleStr];
NSString *categoryStr = #"Comedy";
GDataMediaCategory *mediaCategory = [GDataMediaCategory mediaCategoryWithString:categoryStr];
[mediaCategory setScheme:kGDataSchemeYouTubeCategory];
NSString *descStr = #"Description";
GDataMediaDescription *mediaDesc = [GDataMediaDescription textConstructWithString:descStr];
NSString *keywordsStr = #"iOS";
GDataMediaKeywords *mediaKeywords = [GDataMediaKeywords keywordsWithString:keywordsStr];
GDataYouTubeMediaGroup *mediaGroup = [GDataYouTubeMediaGroup mediaGroup];
[mediaGroup setMediaTitle:mediaTitle];
[mediaGroup setMediaDescription:mediaDesc];
[mediaGroup addMediaCategory:mediaCategory];
[mediaGroup setMediaKeywords:mediaKeywords];
[mediaGroup setIsPrivate:isPrivate];
NSString *mimeType = [GDataUtilities MIMETypeForFileAtPath:self.videoPath
defaultMIMEType:#"video/mp4"];
GDataEntryYouTubeUpload *entry = [GDataEntryYouTubeUpload uploadEntryWithMediaGroup:mediaGroup
data:data
MIMEType:mimeType
slug:filename];
GDataServiceTicket *ticket = [service fetchEntryByInsertingEntry:entry
forFeedURL:url
delegate:self
didFinishSelector:#selector(uploadTicket:finishedWithEntry:error:)];
[self setUploadTicket:ticket];
And I'm having this response:
serviceBase: objectFetcher:GTMHTTPUploadFetcher 0x48af0a0 (https://uploads.gdata.youtube.com/resumable/feeds/api/users/myCoolMail#gmail.com/uploads?upload_id=heregoesidiremoved) failedWithStatus:400 data:GDataInvalidRequestUriExceptionException message unavailable
I've tried Google sample code and had the same result. I used device and Simulator (5.0). I've tried prepared video as long as the recorded from iPhone one.
I created the Project in the google API section and got an application key.
Please, help me find the solution of the problem!
The problem was here:
NSString *username = service.username;
NSURL *url = [GDataServiceGoogleYouTube youTubeUploadURLForUserID:username];
Don't know why is that, but I've changed the userID from "username" to kGDataServiceDefaultUser and the thing started working. So simple and so odd, but it did the trick.
Correct code:
NSURL *url = [GDataServiceGoogleYouTube youTubeUploadURLForUserID:kGDataServiceDefaultUser];
I want to upload video on youtube from my iphone app..
I have tried this http://urinieto.com/2010/10/upload-videos-to-youtube-with-iphone-custom-app/
but in the end i am getting error
Domain=com.google.GDataServiceDomain Code=400 "The operation couldn’t be completed. (com.google.GDataServiceDomain error 400.)" UserInfo=0x4d921f0 {}
Can any one help me.
Thanx!!!
My code
NSString *devKey = [mDeveloperKeyField text];
GDataServiceGoogleYouTube *service = [self youTubeService];
[service setYouTubeDeveloperKey:devKey];
NSString *username = [mUsernameField text];
NSString *clientID = [mClientIDField text];
NSURL *url = [GDataServiceGoogleYouTube youTubeUploadURLForUserID:username
clientID:clientID];
// load the file data
NSString *path = [[NSBundle mainBundle] pathForResource:#"YouTubeTest" ofType:#"m4v"];
NSData *data = [NSData dataWithContentsOfFile:path];
NSString *filename = [path lastPathComponent];
// gather all the metadata needed for the mediaGroup
NSString *titleStr = [mTitleField text];
GDataMediaTitle *title = [GDataMediaTitle textConstructWithString:titleStr];
NSString *categoryStr = [mCategoryField text];
GDataMediaCategory *category = [GDataMediaCategory mediaCategoryWithString:categoryStr];
[category setScheme:kGDataSchemeYouTubeCategory];
NSString *descStr = [mDescriptionField text];
GDataMediaDescription *desc = [GDataMediaDescription textConstructWithString:descStr];
NSString *keywordsStr = [mKeywordsField text];
GDataMediaKeywords *keywords = [GDataMediaKeywords keywordsWithString:keywordsStr];
BOOL isPrivate = mIsPrivate;
GDataYouTubeMediaGroup *mediaGroup = [GDataYouTubeMediaGroup mediaGroup];
[mediaGroup setMediaTitle:title];
[mediaGroup setMediaDescription:desc];
[mediaGroup addMediaCategory:category];
[mediaGroup setMediaKeywords:keywords];
[mediaGroup setIsPrivate:isPrivate];
NSString *mimeType = [GDataUtilities MIMETypeForFileAtPath:path
defaultMIMEType:#"video/mp4"];
// create the upload entry with the mediaGroup and the file data
GDataEntryYouTubeUpload *entry;
entry = [GDataEntryYouTubeUpload uploadEntryWithMediaGroup:mediaGroup
data:data
MIMEType:mimeType
slug:filename];
SEL progressSel = #selector(ticket:hasDeliveredByteCount:ofTotalByteCount:);
[service setServiceUploadProgressSelector:progressSel];
GDataServiceTicket *ticket;
ticket = [service fetchEntryByInsertingEntry:entry
forFeedURL:url
delegate:self
didFinishSelector:#selector(uploadTicket:finishedWithEntry:error:)];
[self setUploadTicket:ticket];
First things first, check the YouTube API for any updates to it's GData libraries, (they changed last I used them and broke my app).
http://apiblog.youtube.com/2009/02/youtube-apis-iphone-cool-mobile-apps.html
Next, check for silly stuff. Got all your headers imported, everything checks out, etc?
Try setting your info.plist to use Wi-Fi, I've heard some of the new GData API's look for that might explain your 400 error, your app might not be pinging the YouTube servers.
In One of my application i need to add some image in video. so i cut break video in two part and also make one video from that image. now i want to combine this three video file and make one video file. but i am not get any idea to combine this three video. i see some code over here. but that is not helpful to me. for break video and for make video from image i used below code now i want code to merge this all video.
Any other idea for put current view screen in video file in between.
For break video file
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"Affagogato" ofType:#"mp4"]];
AVURLAsset *anAsset = [[AVURLAsset alloc] initWithURL:url options:nil];
for(int i = 0; i < 2; i++) {
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]
initWithAsset:anAsset presetName:AVAssetExportPresetLowQuality];
NSString *filePath = nil;
NSUInteger count = 0;
do {
filePath = NSTemporaryDirectory();
NSString *numberString = count > 0 ? [NSString stringWithFormat:#"-%i", count] : #"";
filePath = [filePath stringByAppendingPathComponent:[NSString stringWithFormat:#"Output-%#.mov", numberString]];
count++;
} while([[NSFileManager defaultManager] fileExistsAtPath:filePath]);
exportSession.outputURL = [NSURL fileURLWithPath:filePath];
exportSession.outputFileType = AVFileTypeQuickTimeMovie;
CMTimeRange range;
if(i == 0){
CMTime start = CMTimeMakeWithSeconds(0.0, 600);
CMTime duration = CMTimeMakeWithSeconds(10.0, 600);
range = CMTimeRangeMake(start, duration);
}else{
CMTime start = CMTimeMakeWithSeconds(10.0, 600);
range = CMTimeRangeMake(start, anAsset.duration);
}
exportSession.timeRange = range;
[exportSession exportAsynchronouslyWithCompletionHandler:^
{
dispatch_async(dispatch_get_main_queue(), ^{
[self exportDidFinish:exportSession Tag:i];
});
}];
}
Get video from Images
CGRect rect=CGRectMake(0, 0, 320, 480);
view = [[UIView alloc]initWithFrame:rect];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSString *path = [documentsDirectory stringByAppendingPathComponent:[#"video2" stringByAppendingString:#".mov"]];
CGSize size = self.view.frame.size;
NSMutableDictionary *attributes = [[NSMutableDictionary alloc]init];
[attributes setObject:[NSNumber numberWithUnsignedInt:kCVPixelFormatType_32ARGB] forKey:(NSString*)kCVPixelBufferPixelFormatTypeKey];
[attributes setObject:[NSNumber numberWithUnsignedInt:320] forKey:(NSString*)kCVPixelBufferWidthKey];
[attributes setObject:[NSNumber numberWithUnsignedInt:480] forKey:(NSString*)kCVPixelBufferHeightKey];
NSError *error = nil;
AVAssetWriter *videoWriter = [[AVAssetWriter alloc] initWithURL:
[NSURL fileURLWithPath:path] fileType:AVFileTypeQuickTimeMovie
error:&error];
NSParameterAssert(videoWriter);
NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
AVVideoCodecH264, AVVideoCodecKey,
[NSNumber numberWithInt:size.width], AVVideoWidthKey,
[NSNumber numberWithInt:size.height], AVVideoHeightKey,
nil];
AVAssetWriterInput* writerInput = [[AVAssetWriterInput
assetWriterInputWithMediaType:AVMediaTypeVideo
outputSettings:videoSettings] retain];
AVAssetWriterInputPixelBufferAdaptor *adaptor = [AVAssetWriterInputPixelBufferAdaptor
assetWriterInputPixelBufferAdaptorWithAssetWriterInput:writerInput
sourcePixelBufferAttributes:nil];
NSParameterAssert(writerInput);
NSParameterAssert([videoWriter canAddInput:writerInput]);
[videoWriter addInput:writerInput];
//Start a session:
[videoWriter startWriting];
[videoWriter startSessionAtSourceTime:kCMTimeZero];
CVPixelBufferRef buffer = NULL;
//convert uiimage to CGImage.
xPixel=0;
yPixel=250;
buffer = [self pixelBufferFromCGImage:[[UIImage imageNamed:#"1.jpeg"] CGImage]];
CVPixelBufferPoolCreatePixelBuffer (NULL, adaptor.pixelBufferPool, &buffer);
[adaptor appendPixelBuffer:buffer withPresentationTime:kCMTimeZero];
for (int i = 0;i<2; i++)
{
if([writerInput isReadyForMoreMediaData])
{
//NSLog(#"inside for loop %d",i);
for(int pframetime=1;pframetime<=2;pframetime++)
{
CMTime frameTime = CMTimeMake(pframetime,25);
CMTime lastTime=CMTimeMake(i,1); //i is from 0 to 19 of the loop above
CMTime presentTime=CMTimeAdd(lastTime, frameTime);
if(i==0)
buffer = [self pixelBufferFromCGImage:[[UIImage imageNamed:#"1.jpeg"] CGImage]];
else
buffer = [self pixelBufferFromCGImage:[[UIImage imageNamed:#"2.jpeg"] CGImage]];
while ( ![writerInput isReadyForMoreMediaData] )
{
[NSThread sleepForTimeInterval:0.05];
}
[adaptor appendPixelBuffer:buffer withPresentationTime:presentTime];
i++;
}
if(buffer)
CVBufferRelease(buffer);
//[NSThread sleepForTimeInterval:0.1];
}
}
[writerInput markAsFinished];
[videoWriter finishWriting];
[videoPathArray addObject:path];
//Finish the session:
[videoWriter release];
[writerInput release];
CVPixelBufferPoolRelease(adaptor.pixelBufferPool);
For Merge video files i try this code but not useful here is some blank screen between video
AVMutableComposition* mixComposition = [AVMutableComposition composition];
NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* video_inputFilePath1 = [videoPathArray objectAtIndex:1];
NSURL* video_inputFileUrl1 = [NSURL fileURLWithPath:video_inputFilePath1];
NSString* video_inputFilePath2 = [videoPathArray objectAtIndex:0];
NSURL* video_inputFileUrl2 = [NSURL fileURLWithPath:video_inputFilePath2];
NSString* video_inputFilePath3 = [videoPathArray objectAtIndex:2];
NSURL* video_inputFileUrl3 = [NSURL fileURLWithPath:video_inputFilePath3];
NSString* outputFileName = #"outputFile.mov";
NSString* outputFilePath = [NSString stringWithFormat:#"%#/%#",documentsDirectoryPath,outputFileName];
NSURL* outputFileUrl = [NSURL fileURLWithPath:outputFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:outputFilePath])
[[NSFileManager defaultManager] removeItemAtPath:outputFilePath error:nil];
CMTime nextClipStartTime = kCMTimeZero;
AVURLAsset* videoAsset1 = [[AVURLAsset alloc]initWithURL:video_inputFileUrl1 options:nil];
AVURLAsset* videoAsset2 = [[AVURLAsset alloc]initWithURL:video_inputFileUrl2 options:nil];
AVURLAsset* videoAsset3 = [[AVURLAsset alloc]initWithURL:video_inputFileUrl3 options:nil];
CMTimeRange video_timeRange1 = CMTimeRangeMake(kCMTimeZero,videoAsset1.duration);
AVMutableCompositionTrack *a_compositionVideoTrack1 = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
[a_compositionVideoTrack1 insertTimeRange:video_timeRange1 ofTrack:[[videoAsset1 tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:nextClipStartTime error:nil];
CMTimeRange video_timeRange3 = CMTimeRangeMake(nextClipStartTime,videoAsset3.duration);
[a_compositionVideoTrack1 insertTimeRange:video_timeRange3 ofTrack:[[videoAsset3 tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:videoAsset1.duration error:nil];
CMTimeRange video_timeRange2 = CMTimeRangeMake(nextClipStartTime,videoAsset1.duration);
[a_compositionVideoTrack1 insertTimeRange:video_timeRange2 ofTrack:[[videoAsset2 tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:videoAsset1.duration error:nil];
AVAssetExportSession* _assetExport = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetLowQuality];
_assetExport.shouldOptimizeForNetworkUse = YES;
_assetExport.outputFileType = #"com.apple.quicktime-movie";
_assetExport.outputURL = outputFileUrl;
Try watching the video called "Working with Media in AV Foundation" in the apple developers portal. It tells you how to do what you are describing.
https://developer.apple.com/videos/wwdc/2011/