Playing a local video using AVPlayer - ios

I just wasted like 3 hours on this and I can't see where I'm going wrong.
I'm trying to play a video I have stored locally using AVPlayer. This is how I launch the player:
- (void)openVideo:(NSURL *)videoURL {
NSLog(#"Playing video with the url:\n%#", videoURL);
AVPlayer *player = [AVPlayer playerWithURL:videoURL];
AVPlayerViewController *playerViewController = [AVPlayerViewController new];
playerViewController.player = player;
[self presentViewController:playerViewController animated:YES completion:nil];
}
And this is the NSURL I'm passing:
+ (NSURL *)getURL:(NSString *)itemKey withType:(NSString *)itemType {
NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *dataFilePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: [NSString stringWithFormat:#"%#.%#", itemKey, itemType]]];
NSURL *itemURL;
if ([[NSFileManager defaultManager] fileExistsAtPath: dataFilePath]){ // if data exists
itemURL = [NSURL fileURLWithPath:dataFilePath];
}
else {
NSLog(#"The data requested does not exist! Returning an empty url file...");
itemURL = nil;
}
return itemURL;
}
When I run openVideo, the output I get is:
Playing video with the url:
/var/mobile/Containers/Data/Application/72C35DC4-9EF1-4924-91F4-EDA4BDB6AAD3/Documents/sample.vid
But I keep getting a disabled video player..
What am I doing wrong?

Finally figured the issue out. I was downloading my files and storing them as NSData, and had to use writeToFile and specify the correct extension to read them correctly.
NSString *saveFilePath; = [NSTemporaryDirectory()stringByAppendingPathComponent:#"temp.mp4"];
[fileData writeToFile:saveFilePath atomically:YES];
NSURL *filepath = [NSURL fileURLWithPath:saveFilePath];
AVPlayer *player = [AVPlayer playerWithURL:filepath];
Hopefully this helps someone out there.

Related

Download Audio file from URL and play it in iOS App

I have an URL which I get from JSON response, When I hit the URL in browser the file is downloaded, Now am wondering how can I play such URL which is a Download URL.I've been looking around many post But none of them could help me.
type of url am getting : http://www.smartivr.in/sounds/voicemail/download/f77245d9-e7ee-4424-850c-6a45022d0a54_1
Below is the code I tried.
NSString *audio=[NSString stringWithFormat:#"%#.mp3",cell.url];
NSLog(#"url:%#",audio);
NSURL *url = [NSURL fileURLWithPath:audio];
NSData *soundData = [NSData dataWithContentsOfURL:url];
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0]
stringByAppendingPathComponent:#"sound.caf"];
[soundData writeToFile:filePath atomically:YES];
NSError *error;
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL
fileURLWithPath:filePath] error:&error];
[_audioPlayer play];
NSLog(#"error %#", error);
Try this:
//download your audio file
NSString *urlString = #"http://www.smartivr.in/sounds/voicemail/download/f77245d9-e7ee-4424-850c-6a45022d0a54_1.mp3";
NSURL *url = [NSURL fileURLWithPath:urlString];
NSData *soundData = [NSData dataWithContentsOfURL:url];
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0]
stringByAppendingPathComponent:#"sound.caf"];
[soundData writeToFile:filePath atomically:YES];
// get the file from directory
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *documentsDirectory = [pathArray objectAtIndex:0];
NSString *soundPath = [documentsDirectory stringByAppendingPathComponent:#"sound.caf"];
NSURL *soundUrl;
if ([[NSFileManager defaultManager] fileExistsAtPath:soundPath])
{
soundUrl = [NSURL fileURLWithPath:soundPath isDirectory:NO];
}
// play audio file
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
[audioPlayer prepareToPlay];
[audioPlayer play];
You should download your audio file asynchronously.
Thank You Dipankar Das for you help.
I am posting the whole solution here.
which worked for me absolutely.
NSString *audio=#"http://www.smartivr.in/sounds/voicemail/download/f77245d9-e7ee-4424-850c-6a45022d0a54_1.mp3";
NSURL *url = [NSURL URLWithString:audio];
NSData *soundData = [NSData dataWithContentsOfURL:url];
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0]
stringByAppendingPathComponent:#"sound.caf"];
[soundData writeToFile:filePath atomically:YES];
// get the file from directory
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *documentsDirectory = [pathArray objectAtIndex:0];
NSString *soundPath = [documentsDirectory stringByAppendingPathComponent:#"sound.caf"];
NSURL *soundUrl;
if ([[NSFileManager defaultManager] fileExistsAtPath:soundPath])
{
soundUrl = [NSURL fileURLWithPath:soundPath isDirectory:NO];
}
// plau audio file
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
[_audioPlayer prepareToPlay];
[_audioPlayer play];
[_audioPlayer setVolume:5.0];
try use AVPlayer or AVPlayerViewController, you can use direct URL to play mp3 files
even with local file as you will first download it to device, then play from local URL
do not forget that object AVPlayer has to be as property of your Class not local object because of auto-releasing, so declare your player variable in class and set in function not just locally in function and try to play ...
[update]
more details how to do it -> How to play video with AVPlayerViewController (AVKit) in Swift
Here is the mistake
NSString *audio=[NSString stringWithFormat:#"%#.mp3",cell.url];
NSURL *url = [NSURL fileURLWithPath:audio];
I assume that it is a remote url and you cannot treat it as a file url. So you must use
NSURL *url = [NSURL urlWithString:audio];

Play video from coredata as nsdata in avplayer

How to play video in AVPlayer from coredata as nsdata formate?
MPMoviePlayerController deprecated so I am going with AVPlayer. I am search some thing said about url path for saved nsdata location I am not clear about that. Anyone explain this? How can I play?
I am new for this I appreciate if share that code.
If any one share good tutorial for custom AVPlayer I didn't find good one so learn from github sample project.
Advance Thanks :)
You can try this!
NSString *filePath = [self documentsPathForFileName:#"video.mp4"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
if(!fileExists) {
NSData *videoAsData; // your data here
[videoAsData writeToFile:filePath atomically:YES];
}
// access video as URL
NSURL *videoFileURL = [NSURL fileURLWithPath:filePath];
// create an AVPlayer
AVPlayer *player = [AVPlayer playerWithURL:videoFileURL];
// create a player view controller
AVPlayerViewController *controller = [[AVPlayerViewController alloc]init];
controller.player = player;
[self presentViewController:controller animated:YES completion:^{
[controller.player play];
}];
- (NSString *)documentsPathForFileName:(NSString *)name
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
return [documentsPath stringByAppendingPathComponent:name];
}
// if you want to remove file after playing video
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
BOOL success = [fileManager removeItemAtPath:filePath error:&error];
Here's a Swift version on how to do this
let data = //... your video Data/NSData
let cacheURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.appendingPathComponent("yourvidename.mp4")
do {
try data.write(to: cacheURL, options: .atomicWrite)
} catch let err {
print("Failed with error:", err.localizedString)
}
// instantiate the player
let player = AVPlayer(url: cacheURL)
let vcPlayer = AVPlayerViewController()
vcPlayer.player = player
vcPlayer.player?.play()
// present it or add it to whatever view you need
present(vcPlayer, animated: true, completion: nil)
Then on viewWillDisappear delete the content of the cachesDirectory if you want

Storing and retrieving temporary mp4 files

I am capturing a five seconds long mp4 file. I would for the User to be able to play and review the video before uploading it to Parse. I don't want to save the video to the local photo library, I just want to replay. Should I be saving the file to the temporary directory like so:
NSString *outputPath = [NSTemporaryDirectory() stringByAppendingPathComponent:#"output.mov"];
NSURL *outputURL = [[NSURL alloc] initFileURLWithPath:outputPath];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:outputPath])
{
NSError *error;
if ([fileManager removeItemAtPath:outputPath error:&error] == NO){
NSLog(#"File removed from outputPath");
};
}
[MovieFileOutput startRecordingToOutputFileURL:[NSURL fileURLWithPath:outputPath]
recordingDelegate:self];
Can I play the video using this method?
- (IBAction)playVideo:(id)sender {
NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:#"Output.mp4"];
NSURL *fileURL = [NSURL URLWithString:filePath];
self.avPlayer = [AVPlayer playerWithURL:fileURL];
AVPlayerLayer *movieLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
self.avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;
[_avPlayer play];
}

iOS: How to save a video in your directory and play it afterwards?

I am working in an iOS project. I want may application to download a video from the internet programmatically. Then I want to play it. I know how can I play a local video from the Resources, but my question is how could I download it , and the find it to be played.
I am using MPMoviePlayerController to run the video.
Thanking in advance
I found the answer
here I saved the video
NSString *stringURL = #"http://videoURL";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
NSString *documentsDirectory ;
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"videoName.mp4"];
[urlData writeToFile:filePath atomically:YES];
}
and this code is for playing the video form its directory
NSString *filepath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"videoName.mp4"];
//video URL
NSURL *fileURL = [NSURL fileURLWithPath:filepath];
moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];
[moviePlayerController play];
If you have a valid url of the video, Apple provides an API to directly buffer videos with NSURL.
You should hold a reference to the MPMoviePlayerController object from the controller so that ARC doesn't release the object.
#property (nonatomic,strong) MPMoviePlayerController* mc;
Make the URL
NSURL *url = [NSURL URLWithString:#"http://www.example.com/video.mp4"];
Init MPMoviePlayerController with that URL
MPMoviePlayerController *controller = [[MPMoviePlayerController alloc] initWithContentURL:url];
Resize the controller, add it to your view, play it and enjoy the video.
self.mc = controller; // so that ARC doesn't release the controller
controller.view.frame = self.view.bounds;
[self.view addSubview:controller.view];
[controller play]; //Start playing
For more detail you can visit this playing video from a url in ios7

Play mp3 files with AVAudioPlayer with PlayAndRecord category?

Hi I have a setup that records audio (with AVAudioSessionCategoryPlayAndRecord category), now I want to playback and MP3 file as usual with AVAudioPlayer instance, but no any sound can be hear.
AVAudioPlayer do not throw any error, nor in its delegate callbacks.
Has anybody similar experience? How to overcome this?
Please use this -
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
filePath = [NSString stringWithFormat:#"%#/%#.mp3", docDirPath , #"Welcome"];
NSError *error;
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
if (avPlayer == nil)
{
NSLog(#"AudioPlayer did not load properly: %#", [error description]);
}
else
{
[avPlayer play];
avPlayer.delegate=self;
}
And tell me if it is working or not.

Resources