I've created a custom camera similar to snapchat with AVFoundation. The picture aspect works: take a picture and I display the picture. Now I'm trying to take a video and display the video.
I have captured a successful video file, tested and works with MPMoviePlayer, but am unable to play it back on AVPlayer.
- (void)takeVideoAction:(id)sender {
NSString *outputPath = [NSTemporaryDirectory() stringByAppendingPathComponent:#"output.mp4"];
NSFileManager *manager = [[NSFileManager alloc] init];
if ([manager fileExistsAtPath:outputPath]){
[manager removeItemAtPath:outputPath error:nil];
}
[movieFileOutput startRecordingToOutputFileURL:[NSURL fileURLWithPath:outputPath] recordingDelegate:self];
}
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error{
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:outputFileURL options:nil];
[asset loadValuesAsynchronouslyForKeys:#[#"tracks"] completionHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
NSError *error = nil;
if([asset statusOfValueForKey:#"tracks" error:&error] == AVKeyValueStatusFailed){
NSLog(#"error: %#", [error description]);
}
else{
self.playerItem = [AVPlayerItem playerItemWithAsset:asset];
self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
self.playerLayer.frame = self.view.bounds;
[self.view.layer addSublayer:self.playerLayer];
[self.player play];
}
});
}];
}
This is my first time using AVFoundation & AVPlayer. Is it that I can not [self.player play] after the asset loads right? I need to wait for item status to be AVPlayerItemStatusReadyToPlay?
ERROR: Error Domain=NSURLErrorDomain Code=-1100 "The requested URL was not found on this server."
I am using AVPlayerLayer for playing video. I used the below code and it worked fine.
AVPlayer *avPlayerq = [AVPlayer playerWithURL:NSURL];
avPlayerq.actionAtItemEnd = AVPlayerActionAtItemEndNone;
AVPlayerLayer *videoLayer = [AVPlayerLayer playerLayerWithPlayer:avPlayerq];
videoLayer.frame= self.view.bounds;
videoLayer.videoGravity=AVLayerVideoGravityResizeAspectFill;
[self.view.layer addSublayer:videoLayer];
[avPlayerq play];
Hope this may help you.
Related
I am Playing Audio from URL given below
"http://sumeetmusiclocal.wsisites.net/Songs/Kashyala Lavato (Lavani).mp3"
By Using Code given below
NSString *urlString = #"http://sumeetmusiclocal.wsisites.net/Songs/Kashyala Lavato (Lavani).mp3";
NSURL *audioFileLocationURL = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileLocationURL error:&error];
[audioPlayer setNumberOfLoops:-1];
if (error) {
NSLog(#"%#", [error localizedDescription]);
[[self volumeControl] setEnabled:NO];
[[self playPauseButton] setEnabled:NO];
[[self alertLabel] setText:#"Unable to load file"];
[[self alertLabel] setHidden:NO];
} else {
[[self alertLabel] setText:[NSString stringWithFormat:#"%# has loaded", #"HeadspinLong.caf"]];
[[self alertLabel] setHidden:NO];
//Make sure the system follows our playback status
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
//Load the audio into memory
[audioPlayer prepareToPlay];
}
But I getting Error saying
Printing description of error:
Error Domain=NSOSStatusErrorDomain Code=2003334207 "(null)"
2016-03-08 12:43:45.835 SumeetApp[1839:78581] The operation couldn’t be completed. (OSStatus error 2003334207.)
Can anyone please help me to solve this error or suggest me some other way for playing audio from url.
Thank you
Try This
AVURLAsset *asset = [AVURLAsset assetWithURL:[NSURL URLWithString:#"http://clips.vorwaerts-gmbh.de/VfE_html5.mp4"]];
AVPlayerItem *playerItem1 = [AVPlayerItem playerItemWithAsset:asset];
AVPlayer *player1 = [AVPlayer playerWithPlayerItem:playerItem1];
AVPlayerLayer *playerLayer1 = [AVPlayerLayer playerLayerWithPlayer:player1];
playerLayer1.videoGravity = AVLayerVideoGravityResizeAspectFill;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
playerLayer1.frame = self.view.frame;
});
[self.view.layer insertSublayer:playerLayer1 atIndex:1];
[player1 play];
Hope this work for you.
AVPlayer *player = [[AVPlayer alloc]initWithURL:[NSURL URLWithString:#"http://sumeetmusiclocal.wsisites.net/Songs/Kashyala Lavato (Lavani).mp3"]];
[player play];
Try this code this is working for me.
Try This
NSURL *url = [NSURL URLWithString:#"YOUR_MP3URL"];
self.playerItem = [AVPlayerItem playerItemWithURL:url];
self.player = [AVPlayer playerWithPlayerItem:playerItem];
self.player = [AVPlayer playerWithURL:#"YOUR_MP3URL"];
for play
[self.player play];
Hope this helps.
For Error:
you trying to access a file that didn't exist.
so, initWithContentsOfURL:audioFileLocationURL will return nil.
To play Audio:
NSURL *url = [NSURL URLWithString:#"<URL>];
self.playerItem = [AVPlayerItem playerItemWithURL:url];
self.player = [AVPlayer playerWithPlayerItem:playerItem];
self.player = [AVPlayer playerWithURL:<URL>];
[player play];
I use AVCaptureMovieFileOutput to capture a video file.
- (void)takeVideoAction:(id)sender {
NSString *outputPath = [NSTemporaryDirectory() stringByAppendingPathComponent:#"output.mp4"];
NSFileManager *manager = [[NSFileManager alloc] init];
if ([manager fileExistsAtPath:outputPath]){
[manager removeItemAtPath:outputPath error:nil];
}
[movieFileOutput startRecordingToOutputFileURL:[NSURL fileURLWithPath:outputPath] recordingDelegate:self];
}
And then attempt to play it with AVPlayer, but nothing happens. From what Ive been reading, I think I need to wait for the file to finish loading in the below method instead of trying to play it right away.
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error{
AVAsset *asset = [AVAsset assetWithURL:outputFileURL];
self.playerItem = [[AVPlayerItem alloc]initWithAsset:asset];
self.player = [[AVPlayer alloc] initWithPlayerItem:self.playerItem];
self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
[[[self view] layer] insertSublayer:self.playerLayer atIndex:(int)self.view.layer.sublayers.count];
[self.playerLayer setFrame:self.view.frame];
//self.playerLayer.backgroundColor = [UIColor yellowColor].CGColor;
[self.player play];
}
When I remove the line :
NSFileManager *manager = [[NSFileManager alloc] init];
if ([manager fileExistsAtPath:outputPath]){
[manager removeItemAtPath:outputPath error:nil];
}
it works.
I am trying to play a local video from my app using AVPlayer. I have looked everywhere but can't find any useful tutorials/demos/documentation. Here is what I am trying, but it is not playing. Any idea why? The URL is valid because I was using the same one to play a video using MPMoviePlayer successfully.
Video *currentVideo = [videoArray objectAtIndex:0];
NSString *filepath = currentVideo.videoURL;
NSURL *fileURL = [NSURL fileURLWithPath:filepath];
AVURLAsset *asset = [AVURLAsset assetWithURL: fileURL];
AVPlayerItem *item = [AVPlayerItem playerItemWithAsset: asset];
self.player = [[AVPlayer alloc] initWithPlayerItem: item];
AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:self.player];
self.player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
layer.frame = CGRectMake(0, 0, 1024, 768);
[self.view.layer addSublayer: layer];
[self.player play];
I believe the problem is that you're assuming that after executing this line AVURLAsset *asset = [AVURLAsset assetWithURL: fileURL]; the asset is ready to use. This is not the case as noted in the AV Foundation Programming Guide:
You create an asset from a URL using AVURLAsset. Creating the asset, however,
does not necessarily mean that it’s ready for use. To be used, an asset must
have loaded its tracks.
After creating the asset try loading it's tracks:
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:fileURL options:nil];
NSString *tracksKey = #"tracks";
[asset loadValuesAsynchronouslyForKeys:#[tracksKey] completionHandler:
^{
NSError *error;
AVKeyValueStatus status = [asset statusOfValueForKey:tracksKey error:&error];
if (status == AVKeyValueStatusLoaded) {
// At this point you know the asset is ready
self.playerItem = [AVPlayerItem playerItemWithAsset:asset];
...
}
}];
Please refer to this link to see the complete example.
Hope this helps!
I'm trying to play remote .mp3 file
but its giving the following error.
The operation couldn’t be completed. (OSStatus error -43.)
here is my code :
- (void)viewDidLoad
{
[super viewDidLoad];
isPlaying = NO;
/*
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"Dar-e-Nabi-Per" ofType:#"mp3"]];
*/
NSURL *url = [NSURL
URLWithString:#"http://megdadhashem.wapego.ru/files/56727/tubidy_mp3_e2afc5.mp3"];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error)
{
NSLog(#"Error in audioPlayer: %#",
[error localizedDescription]);
}
else
{
audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
}
}
Can anyone please guide me where i'm doing mistake
For steaming audio from a remote server, use AVPlayer instead of AVAudioPLayer.
AVPlayer Documentation
Sample Code:
- (void)playSampleSong:(NSString *)iSongName {
NSString *aSongURL = [NSString stringWithFormat:#"http://megdadhashem.wapego.ru/files/56727/tubidy_mp3_e2afc5.mp3"];
// NSLog(#"Song URL : %#", aSongURL);
AVPlayerItem *aPlayerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:aSongURL]];
AVPlayer *anAudioStreamer = [[AVPlayer alloc] initWithPlayerItem:aPlayerItem];
[anAudioStreamer play];
// Access Current Time
NSTimeInterval aCurrentTime = CMTimeGetSeconds(anAudioStreamer.currentTime);
// Access Duration
NSTimeInterval aDuration = CMTimeGetSeconds(anAudioStreamer.currentItem.asset.duration);
}
Use this to play song from URL
NSData *songData=[NSData dataWithContentsOfURL:url];
self.player = [[AVAudioPlayer alloc] initWithData:songData error:nil];
self.player.numberOfLoops=0;
_player.delegate=self;
[_player prepareToPlay];
[_player play]
I want to play audio file while recording with camera. I used AVAudioPlayer for playing audio and AVCamCaptureManager for recording.
But when audio starts to play, preview screen is freezing. What should i do?
Thanks for your helping. Here is the code. (I'm working on AVCam example.)
This is preview part.
if ([self captureManager] == nil) {
AVCamCaptureManager *manager = [[AVCamCaptureManager alloc] init];
[self setCaptureManager:manager];
[[self captureManager] setDelegate:self];
if ([[self captureManager] setupSession]) {
AVCaptureVideoPreviewLayer *newCaptureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:[[self captureManager] session]];
UIView *view = [self videoPreviewView];
CALayer *viewLayer = [view layer];
[viewLayer setMasksToBounds:YES];
CGRect bounds = CGRectMake(0, 0, 480, 320);
[newCaptureVideoPreviewLayer setFrame:bounds];
if ([newCaptureVideoPreviewLayer isOrientationSupported]) {
[newCaptureVideoPreviewLayer setOrientation:[DeviceProperties setPreviewOrientation]];
}
[newCaptureVideoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[viewLayer insertSublayer:newCaptureVideoPreviewLayer below:[[viewLayer sublayers] objectAtIndex:0]];
[self setCaptureVideoPreviewLayer:newCaptureVideoPreviewLayer];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[[[self captureManager] session] startRunning];
});
[self updateButtonStates];
}
And this is audio play part.
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"%#", sound] ofType:#"wav"]];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[audioPlayer play];
If I use AudioServicesPlaySystemSound normal without freezing but this time it only works on viewDidLoad.
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef soundFileRef;
soundFileRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) CFBridgingRetain(#"sound"), CFSTR ("wav"), NULL);
UInt32 soundID;
AudioServicesCreateSystemSoundID(soundFileRef, &soundID);
AudioServicesPlaySystemSound(soundID);
My problem wasn't for video but it was for playing a sound while in a call (voip type application) and the answer to this question worked for me:
Using vibrate and AVCaptureSession at the same time
Hope setting AVAudioSession category to AVAudioSessionCategoryPlayAndRecord will solve the problem. And also set its category options to AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionMixWithOthers. Please check the below set of code
#property (strong, nonatomic) AVAudioPlayer *audioPlayer;
NSURL *soundUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"VoicemailSound" ofType:#"mp3"]]; //Download and add a system sound to your project and mention its name and type here
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionMixWithOthers error: nil];
[self.audioPlayer prepareToPlay];
[self.audioPlayer play];