I make a AVQueuePlayer and add some video items . when i run app , video's sound play but video is not showing. i know the reason why video is not showing , it is because i haven't know how to add AVQueuePlayer in the view. Please help me
NSString *firstVideoPath = [[NSBundle mainBundle]
pathForResource:#"3" ofType:#"m4v"];
NSString *secondVideoPath = [[NSBundle mainBundle]
pathForResource:#"2" ofType:#"m4v"];
NSString *thirdVideoPath = [[NSBundle mainBundle]
pathForResource:#"3" ofType:#"m4v"];
AVPlayerItem *firstVideoItem = [AVPlayerItem playerItemWithURL:
[NSURL fileURLWithPath:firstVideoPath]];
AVPlayerItem *secondVideoItem = [AVPlayerItem playerItemWithURL:
[NSURL fileURLWithPath:secondVideoPath]];
AVPlayerItem *thirdVideoItem = [AVPlayerItem playerItemWithURL:
[NSURL fileURLWithPath:thirdVideoPath]];
self.queuePlayer = [AVQueuePlayer queuePlayerWithItems:
[NSArray arrayWithObjects:firstVideoItem,
secondVideoItem,thirdVideoItem,nil]];
[self.playerView setPlayer:self.queuePlayer];
[self.queuePlayer play];
First, grap all your paths:
NSString *firstVideoPath = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"m4v"];
NSString *secondVideoPath = [[NSBundle mainBundle] pathForResource:#"demo" ofType:#"mp4"];
NSString *thirdVideoPath = [[NSBundle mainBundle] pathForResource:#"3" ofType:#"m4v"];
AVPlayerItem *firstVideoItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:firstVideoPath]];
AVPlayerItem *secondVideoItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:secondVideoPath]];
AVPlayerItem *thirdVideoItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:thirdVideoPath]];
Init AVQueuePlayer:
AVQueuePlayer *queuePlayer = [AVQueuePlayer queuePlayerWithItems:#[firstVideoItem, secondVideoItem,thirdVideoItem]];
And finally use layer to display all movies as playlist.
AVPlayerLayer *layer = [AVPlayerLayer layer];
[layer setPlayer:queuePlayer];
[layer setFrame:CGRectMake(10, 10, 300, 200)];
[layer setBackgroundColor:[UIColor redColor].CGColor];
[layer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[self.view.layer addSublayer:layer];
[queuePlayer play];
Don't forget to add frameworks:
#import <QuartzCore/QuartzCore.h>
#import "AVFoundation/AVFoundation.h"
Related
I got this piece of code:
theMoviPlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:#"/Resources/disc.mp4"]];
theMoviPlayer.controlStyle = MPMovieControlStyleFullscreen;
theMoviPlayer.view.transform = CGAffineTransformConcat(theMoviPlayer.view.transform, CGAffineTransformMakeRotation(M_PI_2));
UIWindow *backgroundWindow = [[UIApplication sharedApplication] keyWindow];
[theMoviPlayer.view setFrame:backgroundWindow.frame];
[backgroundWindow addSubview:theMoviPlayer.view];
[theMoviPlayer play];
But i really dont know how to add the video to my project. In which folder do i have to put the video file!? Or do i have to do something else to add it to my project?
EDIT:
It looks like this in xcode, is it correct?
Because i do get a playback error right now.
Previously i used an url to play this video and this worked quite well, but with this file locally not :(
Ok your bundle path looks jacked, below should work.
NSBundle *bundle = [NSBundle mainBundle];
NSString *moviePath = [bundle pathForResource:#"disc" ofType:#"mp4"];
NSURL *movieURL = [[NSURL fileURLWithPath:moviePath] retain];
theMoviPlayer = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
theMoviPlayer.controlStyle = MPMovieControlStyleFullscreen;
theMoviPlayer.view.transform = CGAffineTransformConcat(theMoviPlayer.view.transform, CGAffineTransformMakeRotation(M_PI_2));
UIWindow *backgroundWindow = [[UIApplication sharedApplication] keyWindow];
[theMoviPlayer.view setFrame:backgroundWindow.frame];
[backgroundWindow addSubview:theMoviPlayer.view];
[theMoviPlayer play];
Add MediaPlayer Framework
import it to your file
#import <MediaPlayer/MediaPlayer.h>
Create an object of MPMoviePlayerController
MPMoviePlayerController * moviePlayer;
write this code where you wants to play video
NSString *filepath = [[NSBundle mainBundle] pathForResource:#"spacetest.mp4" ofType:nil];
NSURL *fileURL = [NSURL fileURLWithPath:filepath];
moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];
[self.view addSubview:moviePlayer.view];
moviePlayer.fullscreen = YES;
[moviePlayer play];
Using HTML5 as I promised above:
NSString *videoTitle = #"disc.mp4";
NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
NSString *playPath = [NSString stringWithFormat:#"<center><video width=\"640\" height=\"480\" controls><source src=\"%#\" media=\"all and (max-width:1024px)\"></video></center>",videoTitle];
[webView loadHTMLString:playPath baseURL:baseURL];
This will play in 640x480, but if you are familiar with HTML5 video tags, you can customize pretty heavily.
Since you are using MPMoviePlayerController and not UIWebView you can place your mp4 or file in your Resources and XCode/iOS will find it. Be sure that the directory/group that the file is under is yellow not blue. You don't want it to be a relative path.
Just drag the resource into your project. Copy items into destination is selected, First option of Folders is selected, and most importantly, add to target!
Ok try the code below:
NSBundle *bundle = [NSBundle mainBundle];
NSString *moviePath = [bundle pathForResource:#"disc" ofType:#"mp4"];
NSURL *movieURL = [[NSURL fileURLWithPath:moviePath] retain];
theMoviPlayer = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
theMoviPlayer.controlStyle = MPMovieControlStyleFullscreen;
theMoviPlayer.view.transform = CGAffineTransformConcat(theMoviPlayer.view.transform, CGAffineTransformMakeRotation(M_PI_2));
UIWindow *backgroundWindow = [[UIApplication sharedApplication] keyWindow];
[theMoviPlayer.view setFrame:backgroundWindow.frame];
[backgroundWindow addSubview:theMoviPlayer.view];
[theMoviPlayer play];
I'm new here. I'm already 2 days browsing for solutions, but unhappy.
Here is my code:
NSString *docPath = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *docaPathFull = [docPath stringByAppendingPathComponent:#"/IMG_0003.m4v"];
self.videoURL = [NSURL fileURLWithPath:docaPathFull];
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];
UIImage *thumbnail = [player thumbnailImageAtTime:4.0 timeOption:MPMovieTimeOptionExact];
player = nil;
self.imageView.image = thumbnail;
Problem is, i can't make video file visible for MPMoviePlayerController. I can't get thumbnail and I can't play it, just black player and loading infinity.
I did try:
NSString*thePath=[[NSBundle mainBundle] pathForResource:#"IMG_0003" ofType:#"m4v"];
self.videoURLtheurl=[NSURL fileURLWithPath:thePath];
and this
self.videoURL = [[NSBundle mainBundle] URLForResource:#"IMG_0005" withExtension:#"mov"];
and this
NSString *filePath = #"/Users/[user]/Documents/video/IMG_0004.mov";
self.videoURL = [NSURL fileURLWithPath:filePath];
If you have any ideas how to save my life, please do!!!
Many thanks for you time.
Actually this is my working example from my project. Make sure you added your m4v file to your project. The notification was a need for me, maybe it is not necessary for you.
theMovie = [[MPMoviePlayerController alloc] initWithContentURL:
[NSURL fileURLWithPath: [[NSBundle mainBundle]
pathForResource:#"yourmovie" ofType:#"m4v"]]];
theMovie.view.frame = CGRectMake(0, 0, 320, 480);
[theMovie setControlStyle:MPMovieControlStyleNone];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:theMovie];
[self.view addSubview:theMovie.view];
[theMovie play];
You can use following method to get a thumbnail image for a given Video Url,
-(UIImage *) giveThumbofVideoUrl:(NSURL *) url{
NSString *urlString = [url absoluteString];
AVAsset *asset = [AVAsset assetWithURL:url];
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc]initWithAsset:asset];
imageGenerator.appliesPreferredTrackTransform = YES;
//imageGenerator.maximumSize = CGSizeMake(320,480);
CMTime time = CMTimeMake(1, 1);
CGImageRef imageRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:NULL];
UIImage *image = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return image;
}
How you can use it ?,
NSString*thePath=[[NSBundle mainBundle] pathForResource:#"IMG_0003" ofType:#"m4v"];
NSURL *movieUrl=[NSURL fileURLWithPath:thePath];
UIImage *thumbnail = [self giveThumbofVideoUrl:movieUrl];
MPMoviePlayerController is Deprecated Now. So I have used AVPlayerViewController. and written the following code:
NSURL *videoURL = [NSURL fileURLWithPath:filePath];
//filePath may be from the Bundle or from the Saved file Directory, it is just the path for the video
AVPlayer *player = [AVPlayer playerWithURL:videoURL];
AVPlayerViewController *playerViewController = [AVPlayerViewController new];
playerViewController.player = player;
//[playerViewController.player play];//Used to Play On start
[self presentViewController:playerViewController animated:YES completion:nil];
Please do not forget to import following frameworks:
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
Hope this Helps..
I have created a simple app that triggers 3 different sounds based on the x, y, z axis of the accelorometer, like an instrument. At the moment, if I set the frequency update interval of the accelometer too low, it plays the sound to much, and if I set it too high it it isn't responsive enough. I am a complete beginner to objective c and iphone development, can you tell by the code!..
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional
UIAccelerometer* accelerometer = [UIAccelerometer sharedAccelerometer];
[accelerometer setUpdateInterval: 25.0 / 10.0f];
[[AVAudioSession sharedInstance] setDelegate: self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error: nil];
[accelerometer setDelegate:self];
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
player.volume = 0.5;
player.numberOfLoops = 0;
player.delegate = self;
}
- (void)accelerometer:(UIAccelerometer *)acel didAccelerate:(UIAcceleration *)aceler
{
if (aceler.x > 0.5) {
NSString *fileName = [NSString stringWithFormat:#"snare"];
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:fileName ofType:#"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
NSLog(#"acceleration.x = %+.6f greater", aceler.x);
[player play];
}
else if (aceler.y > 0.5) {
NSString *fileName = [NSString stringWithFormat:#"kick2"];
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:fileName ofType:#"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
NSLog(#"acceleration.y = %+.6f greater", aceler.y);
[player play];
}
else if (aceler.z > 0.5) {
NSString *fileName = [NSString stringWithFormat:#"hat"];
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:fileName ofType:#"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
NSLog(#"acceleration.y = %+.6f greater", aceler.z);
[player play];
}
else {
[player stop];
};
}
Setting the accelerometer's update frequency to a low value wont help here. Imagine the following situation:
time: ------------------------>
real world acceleration event: ___X_____X_____X_____X___
acceleration update: X_____X_____X_____X_____X
sound output started: _________________________
This draft represents a user shaking the device with the same frequency as the accelerometer is updated. But the shake event occurs just in the middle between two accelerometer updates. As a result, the shake events won't be registered and no sound is played.
Consider a high accelerometer update frequency in contrast to the prior approach:
real world acceleration event: ___X_____X_____X_____X___
acceleration update: XXXXXXXXXXXXXXXXXXXXXXXXX
sound output started: ___X_____X_____X_____X___
Basically all real world events result in a sound play within this situation.
The amended code is the following:
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"viewDidLoad");
UIAccelerometer* accelerometer = [UIAccelerometer sharedAccelerometer];
//[accelerometer setUpdateInterval: 25.0 / 10.0f];
[accelerometer setUpdateInterval: 0.01f];
[[AVAudioSession sharedInstance] setDelegate: self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error: nil];
[accelerometer setDelegate:self];
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
//player.volume = 0.5;
//player.numberOfLoops = 0;
//player.delegate = self;
}
- (void)accelerometer:(UIAccelerometer *)acel didAccelerate:(UIAcceleration *)aceler
{
if ((aceler.x > ACC_THRESHOLD)&&((playerX == nil)||(playerX.isPlaying == NO))) {
NSString *fileName = [NSString stringWithFormat:#"snare"];
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:fileName ofType:#"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
playerX = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
NSLog(#"acceleration.x = %+.6f greater", aceler.x);
playerX.delegate = self;
[playerX play];
}
if ((aceler.y > ACC_THRESHOLD)&&((playerY == nil)||(playerY.isPlaying == NO))) {
NSString *fileName = [NSString stringWithFormat:#"kick2"];
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:fileName ofType:#"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
playerY = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
NSLog(#"acceleration.y = %+.6f greater", aceler.y);
playerY.delegate = self;
[playerY play];
}
if ((aceler.z > ACC_THRESHOLD)&&((playerZ== nil)||(playerZ.isPlaying == NO))) {
NSString *fileName = [NSString stringWithFormat:#"hat"];
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:fileName ofType:#"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
playerZ = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
NSLog(#"acceleration.z = %+.6f greater", aceler.z);
playerZ.delegate = self;
[playerZ play];
}
//else {
// [player stop];
//};
}
Please note, that multiple sound plays may be triggered by just one event as each dimension is evaluated separately now. A constant has been introduced by #define ACC_THRESHOLD 0.5f. A new sound play for one dimension is started only, after a previous play finished.
After these general change of event handling you may start optimizations with a signal filter.
Additionally you may use AVAudioPlayer's delegate methods for more detailed sound handling:
#pragma mark -
#pragma mark AVAudioPlayerDelegate methods
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
NSLog(#"audioPlayerDidFinishPlaying: %i", flag);
}
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error{
NSLog(#"audioPlayerDecodeErrorDidOccur: %#", error.description);
}
I have several MP3 files in the user's documents directory, and I want to be able to get and display the ID3 Artwork Tags. I have tried using NSURLAsset, but I am unsure how to convert that to a UIImage or a UIImageView!
Thanks!
You have to use the AVAsset class:
For instance:
NSString *mp3Path = [[NSBundle mainBundle] pathForResource:#"audio-file" ofType:#"mp3"];
NSURL *url = [NSURL fileURLWithPath:mp3Path];
AVAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
for (NSString *format in [asset availableMetadataFormats]) {
for (AVMetadataItem *item in [asset metadataForFormat:format]) {
if ([[item commonKey] isEqualToString:#"artwork"]) {
NSData *data = [(NSDictionary *)[item value] objectForKey:#"data"];
UIImageView *img = [[[UIImageView alloc] initWithImage:[UIImage imageWithData:data]] autorelease];
[self.view addSubview:img];
continue;
}
NSLog(#"%#", item);
}
}
NSLog(#"> Duration = %.2f seconds", CMTimeGetSeconds(asset.duration));
I am already using the MediaPlayer framework but the media player can only be initialized through a URL. I have my video saved in my project, so how can I play it?
URLs can be files paths too (file://):
NSURL *movieURL = [[NSBundle mainBundle] URLForResource:#"movie" withExtension:#"mp4"];
You can also play your video in UIWebview.
CGRect webFrame = CGRectMake(0.0, 0.0, 1, 1);
UIWebView *webView = [[UIWebView alloc] initWithFrame:webFrame];
[webView setBackgroundColor:[UIColor whiteColor]];
webView.scalesPageToFit =YES;
webView.autoresizingMask =YES;
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"test123" ofType:#"mp4"]isDirectory:NO]]];
[self.view insertSubview:webView atIndex:0];
I am trying to play video inside a UIView, so my first step was to add a class for that view and start playing a movie in it using this code:
- (IBAction)movie:(id)sender{
NSBundle *bundle = [NSBundle mainBundle];
NSString *moviePath = [bundle pathForResource:#"Movie" ofType:#"m4v"];
NSURL *movieURL = [[NSURL fileURLWithPath:moviePath] retain];
MPMoviePlayerController *theMovie = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
theMovie.scalingMode = MPMovieScalingModeAspectFill;
[theMovie play];
}