I m downloading a aac file and playing it in MPMoviePlayerController with following code
movieController = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:self.filePath]];
[self.view addSubview:movieController.view];
CGRect screenBound = [[UIScreen mainScreen] bounds];
CGSize screenSize = screenBound.size;
movieController.view.frame = CGRectMake(0,0,screenSize.width, screenSize.height);
[movieController setFullscreen:YES];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(doneBtnMediaPlayer:) name:MPMoviePlayerWillExitFullscreenNotification object:nil];
movieController is (nonatomic,strong) class property
this works fine in all iOSes except iOS 5 (and iOS 5 simulator).
In iOS 5 it shows black screen and file is played in background.
Another thing i have noticed is, when i run application over already existing app then its works fine on iOS5 also. But when i delete app from device and then run it, at that time it just shows black screen.
See if this helps:
this is your header (.h) file
#import
#import
#interface ViewController : UIViewController
#property(nonatomic,retain)MPMoviePlayerViewController *playerController;
#end
and this is your implementation file (.m)
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize playerController;
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"gold etche" ofType:#"mov"]];
playerController = [[MPMoviePlayerViewController alloc]initWithContentURL:url];
[self presentMoviePlayerViewControllerAnimated:playerController];
[self.view insertSubview:playerController.view atIndex:0];
playerController.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
playerController.moviePlayer.controlStyle = MPMovieControlStyleDefault;
playerController.moviePlayer.scalingMode = MPMovieScalingModeNone;
[playerController.moviePlayer play];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end
I tested this in IOS 5 (5.0 AND 5.1) AND IOS 6 AND EVERYTHING SEEMS TO BE FINE
Related
I am trying to follow this tutorial link, but i have issues. Can somebody please have a look and let me know what needs to be changed.
I tried to looking up other examples but none seems to work. Please let me know what needs to be changed.
The following is the error
Undefined symbols for architecture i386:
"_OBJC_CLASS_$_MPMoviePlayerController", referenced from:
objc-class-ref in VideoScreenViewController.o
"_MPMoviePlayerPlaybackDidFinishNotification", referenced from:
-[VideoScreenViewController playVideo:] in VideoScreenViewController.o
-[VideoScreenViewController moviePlayBackDidFinish:] in VideoScreenViewController.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Here is the code
// VideoScreenViewController.h
#import <UIKit/UIKit.h>
#import "MediaPlayer/MediaPlayer.h"
#interface VideoScreenViewController : UIViewController
#property (strong, nonatomic) MPMoviePlayerController *moviePlayer;
- (IBAction)playVideo:(id)sender;
#end
}
#import "VideoScreenViewController.h"
#import "MediaPlayer/MediaPlayer.h"
#interface VideoScreenViewController ()
#end
#implementation VideoScreenViewController
#synthesize moviePlayer;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
self.view.backgroundColor = [UIColor clearColor];
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)playVideo:(id)sender {
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"Movie" ofType:#"MOV"]];
moviePlayer = [[MPMoviePlayerController alloc]
initWithContentURL:url];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:moviePlayer];
moviePlayer.controlStyle = MPMovieControlStyleDefault;
moviePlayer.shouldAutoplay = YES;
[self.view addSubview:moviePlayer.view];
[moviePlayer setFullscreen:YES animated:YES];
}
- (void) moviePlayBackDidFinish:(NSNotification*)notification {
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"Movie" ofType:#"MOV"]];
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:url];
[[NSNotificationCenter defaultCenter]
removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:player];
if ([player
respondsToSelector:#selector(setFullscreen:animated:)])
{
[player.view removeFromSuperview];
}
}
#end
Add MediaPlayer.framework to your project..and then try..
i had the same problem today and i found out that the media player framework has to be added correctly: so at first right click on "frameworks" click on "add files to.."
located the framework within the folder "developers/Platforms....etpp" then click on "create folder references for any added folders" and click "add" finally - thats it. After this the error did not appear anymore.
Following the Ray Wenderlich tutorial, I've incorporated the latest AdWhirl folders, deleted the adapters I'm not using, setup an account with iAd, uploaded a few house banners, configured the AdWhirl delivery and implemented the retrieve/display code in my Cocos2d app. My logs show that ads are being retrieved successfully but they do not appear on the screen. I'm thinking either they are displayed off screen (no man's land) or are hidden behind a CCLayer. Any suggestions for how to test/resolve this is much appreciated. It's a landscape only orientation if that helps.
Update: the RW tutorial is out of date for Cocos2d version 2.0 users...see below for the solution
Here is my AdWhirl code:
Library.h
#import "AdWhirlView.h"
#import "AdWhirlDelegateProtocol.h"
#import "RootViewController.h"
#interface Library : CCLayer <AdWhirlDelegate>{
this is what the tutorial said but is outdated
//RootViewController *viewController;
this is what is needed instead
UINavigationController *viewController
AdWhirlView *adWhirlView;
enum GameStatePP _state; }
#property(nonatomic,retain) AdWhirlView *adWhirlView;
#property(nonatomic) enum GameStatePP state;
Library.mm
#implementation Library
#synthesize state = _state, adWhirlView;
In Init
self.state = kGameStatePlaying;
Then the AdWhirl methods
- (void)adWhirlWillPresentFullScreenModal {
if (self.state == kGameStatePlaying) {
[[CCDirector sharedDirector] pause];} }
- (void)adWhirlDidDismissFullScreenModal {
if (self.state == kGameStatePaused)
return;
else {
self.state = kGameStatePlaying;
[[CCDirector sharedDirector] resume]; }}
- (NSString *)adWhirlApplicationKey {
return #"myadWhirlKeyGoesHere"; }
- (UIViewController *)viewControllerForPresentingModalView {
return viewController;}
-(void)adjustAdSize {
[UIView beginAnimations:#"AdResize" context:nil];
[UIView setAnimationDuration:0.2];
CGSize adSize = [adWhirlView actualAdSize];
CGRect newFrame = adWhirlView.frame;
newFrame.size.height = adSize.height;
CGSize winSize = [CCDirector sharedDirector].winSize;
newFrame.size.width = winSize.width;
newFrame.origin.x = (self.adWhirlView.bounds.size.width - adSize.width)/2;
newFrame.origin.y = (winSize.height - adSize.height);
adWhirlView.frame = newFrame;
[UIView commitAnimations]; }
- (void)adWhirlDidReceiveAd:(AdWhirlView *)adWhirlVieww {
[adWhirlView rotateToOrientation:UIInterfaceOrientationLandscapeRight];
[self adjustAdSize];
NSLog(#"Library - adWhirlDidReceiveAd");
NSLog(#"%#",[adWhirlView mostRecentNetworkName]); }
-(void)adWhirlDidFailToReceiveAd:(AdWhirlView *)adWhirlVieww usingBackup:(BOOL)yesOrNo {
NSLog(#"Library - adWhirlDidFailToReceiveAd");
NSLog(#"%#",[adWhirlView mostRecentNetworkName]); }
-(void)onEnter {
this is what the tutorial said and is wrong for version Cocos2d 2.0 users
//viewController = [(AppDelegate *)[[UIApplication sharedApplication] delegate] viewController];
this is the correct way
viewController = [(AppDelegate *)[[UIApplication sharedApplication] delegate] navController];
self.adWhirlView = [AdWhirlView requestAdWhirlViewWithDelegate:self];
self.adWhirlView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
[adWhirlView updateAdWhirlConfig];
CGSize adSize = [adWhirlView actualAdSize];
CGSize winSize = [CCDirector sharedDirector].winSize;
self.adWhirlView.frame = CGRectMake((winSize.width/2)-(adSize.width/2),winSize.height-adSize.height,winSize.width,adSize.height);
self.adWhirlView.clipsToBounds = YES;
[viewController.view addSubview:adWhirlView];
[viewController.view bringSubviewToFront:adWhirlView];
[super onEnter]; }
-(void)onExit {
if (adWhirlView) {
[adWhirlView removeFromSuperview];
[adWhirlView replaceBannerViewWith:nil];
[adWhirlView ignoreNewAdRequests];
[adWhirlView setDelegate:nil];
self.adWhirlView = nil;
}
[super onExit]; }
- (void) dealloc {
self.adWhirlView.delegate = nil;
self.adWhirlView = nil; }
In My AppDelegate.h
Wrong:
//RootViewController *viewController;
//UIViewController *viewController;
this is right and is provided in the 2.0 Cocos2d template so doesn't need to be added, just needs to be used:
UINavigationController *navController_;
And so these are not needed
//#property (nonatomic, retain) RootViewController *viewController;
//#property (nonatomic, retain) UIViewController *viewController;
AppDelegate.mm
#synthesize window=window_, navController=navController_, director=director_;
not needed because we will be using the navController instead:
//viewController = viewController_;
DidFinishLaunchingWithOptions (with all references to viewController commented out)
//viewController = [[UIViewController alloc] initWithNibName:nil bundle:nil];
//viewController.wantsFullScreenLayout = YES;
CCGLView *glView = [CCGLView viewWithFrame:[window_ bounds]
pixelFormat:kEAGLColorFormatRGB565
depthFormat:0
preserveBackbuffer:NO
sharegroup:nil
multiSampling:NO
numberOfSamples:0];
director_ = (CCDirectorIOS*) [CCDirector sharedDirector];
director_.wantsFullScreenLayout = YES;
[director_ setDisplayStats:NO];
[director_ setAnimationInterval:1.0/60];
[director_ setDelegate:self];
[director_ setProjection:kCCDirectorProjection2D];
[director_ setView:glView];
if( ! [director_ enableRetinaDisplay:YES] )CCLOG(#"Retina Display Not supported");
navController_ = [[UINavigationController alloc] initWithRootViewController:director_];
navController_.navigationBarHidden = YES;
this is the important line, setting the navController
[window_ addSubview:navController_.view];
[glView setMultipleTouchEnabled:YES];
//[viewController_ setView:glView];
//[window_ addSubview:viewController_.view];
[window_ makeKeyAndVisible];
[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA8888];
[CCFileUtils setiPadSuffix:#"-ipad"];
[CCFileUtils setRetinaDisplaySuffix:#"-hd"];
[CCTexture2D PVRImagesHavePremultipliedAlpha:YES];
[director_ pushScene: [TitleScene scene]];
return YES;
You specify the viewController with this line:
viewController = [(AppDelegate *)[[UIApplication sharedApplication] delegate] viewController];
Are you sure that your appDelegate is setting its viewController property? In other words, is viewController nil? I would check that.
If you still have this problem, use the code below.
Your previous is
[viewController.view addSubview:adWhirlView];<br>
[viewController.view bringSubviewToFront:adWhirlView];
My suggestion is
[[CCDirector sharedDirector].view addSubview:adWhirlView];<br>
[[CCDirector sharedDirector].view bringSubviewToFront:adWhirlView];
Maybe, after that can you see ads.
I have a navigation controller that pushes another view which plays video files. Everything is working fine and on the simulator there is no problem at all. The problem is when I test the application on the iPhone, the movies play well but if I press the home button on the iPhone then I launch the app again I receive the following warning in Xcode Debugging area:
2011-11-21 20:23:05.216 KMW[324:707] MP _playbackInterruptionDidEndNotification :: NSConcreteNotification 0x164e90 {name = AVController_PlaybackInterruptionDidEndNotification;
object = ; userInfo = {
"AVController_InterruptionStatusNotificationParameter" = "non-resumable.SoloAmbientSound";
"AVController_InterruptorNameNotificationParameter" = "AudioSession-324"; }}, _state = 0
Although this warning is appearing I can continue using the App and watch movies without any problem but I am afraid that in a certain situation this warning causes a problem. Here is how I am setting up the view that plays the movies:
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSString *path = [[NSBundle mainBundle] pathForResource:#"movieFileName" ofType:#"m4v"];
movieURL = [NSURL fileURLWithPath:path];
self.moviePlayer = [[[MPMoviePlayerController alloc] initWithContentURL:movieURL] autorelease];
[self.view addSubview:moviePlayer.view];
moviePlayer.view.frame = CGRectMake(0, 10, 320, 181);
[moviePlayer setControlStyle:MPMovieControlStyleNone];
[moviePlayer play];
}
- (void) viewWillDisappear:(BOOL)animated
{
[moviePlayer stop];
[moviePlayer.view removeFromSuperview];
}
- (void)dealloc
{
[movieURL release];
[moviePlayer release];
[super dealloc];
}
Any ideas about this strange warning?
I am trying to play music in my application. The music works fine but after switching viewControllers and returning to the main menu, my music plays again! It means several identical sounds play together! How can I solve this? Here is my code :
- (void)viewDidLoad {
NSString *music = [[NSBundle mainBundle] pathForResource:#"1music" ofType:#"mp3"];
myMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:music] error:NULL];
myMusic.delegate = self;
myMusic.numberOfLoops = -1;
[myMusic play];
}
- (IBAction) scoreView {
ScoreViewController *scoreView = [[ScoreViewController alloc] initWithNibName:#"ScoreViewController" bundle:nil];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.view cache:YES];
[self.view addSubview: scoreView.view];
[UIView commitAnimations];
}
EDITED CODE :
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
NSString * musicSonati = [[NSBundle mainBundle] pathForResource:#"music" ofType:#"mp3"];
myMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:musicSonati] error:NULL];
myMusic.delegate = self;
myMusic.numberOfLoops = -1;
[myMusic play];
}
return self;
}
//toggle button
- (IBAction)MusicPlaying:(id)sender {
if ((isPlay = !isPlay))
{
UIImage *buttonImageNormal = [UIImage imageNamed:#"play.png"];
UIImage *stretchableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:0 topCapHeight:0];
[MusicButton setBackgroundImage:stretchableButtonImageNormal forState:UIControlStateNormal];
[myMusic pause];
}else {
UIImage *buttonImageNormal = [UIImage imageNamed:#"pause.png"];
UIImage *stretchableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:0 topCapHeight:0];
[MusicButton setBackgroundImage:stretchableButtonImageNormal forState:UIControlStateNormal];
NSLog(#"Music play");
[myMusic play];
}
}
If you have audio to play on multiple places then one simple way to achieve this is declare AVAudioPlayer instance in delegate with property synthesized.If you want to play this anywhere do this:-
MyAppDelegate *app_delegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
if(app_delegate.audioPlayer)
{
[app_delegate.audioPlayer release];
app_delegate.audioPlayer = nil;
}
app_delegate.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
and if you want to stop sound do this:-
if(app_delegate.audioPlayer)
{
if([app_delegate.audioPlayer isPlaying])
{
[app_delegate.audioPlayer stop];
[app_delegate.audioPlayer setCurrentTime:0];
}
}
and to play new sound file release and nil same player if already allocated or alloc it again with new sound file url.
Make sure myMusic is correctly declared as a retained property and synthesized then try something like this:
-(void) commonInit {
NSString * musicSonati = [[NSBundle mainBundle] pathForResource:#"music" ofType:#"mp3"];
self.myMusic = [[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:musicSonati] error:NULL] autorelease];
self.myMusic.delegate = self;
self.myMusic.numberOfLoops = -1;
//You probably don't want to play music on init, rather defer to viewDidLoad.
// [self.myMusic play];
}
- (id)initWithCoder:(NSCoder *)coder {
self = [super initWithCoder:coder];
if (self) {
[self commonInit];
}
return self;
}
- (id)init {
self = [super init];
if (self) {
[self commonInit];
}
return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
[self commonInit];
}
return self;
}
Then try this in your viewDidLoad:
- (void)viewDidLoad {
...
if (!self.myMusic.playing) {
[self.myMusic play];
}
...
}
Also, don't forget to release your player in dealloc!
First, viewDidLoad probably isn't a good place to be initializing your AVAudioPlayer, as the system may need to unload some of your components to reclaim memory (in viewDidUnload). You should probably be creating the AVAudioPlayer in your init method or similar.
So what's happening is you end up creating a second AVAudioPlayer when the focus comes back to your application, and you're actually losing the reference to your first one. (Thus, also leaking memory.)
If you want to start playing music when the view loads, you should additionally check its status before doing so:
- (void)viewDidLoad {
...
if (!myMusic.playing) {
[myMusic play];
}
...
}
Its seems you are developing game (from your function name After viewLoad (ScoreView). ;) )
Well, According to me, AvAudioplayer is not Good Option if you want to implement with Game.
Use cocosdenshion, Download the latest cocos2d folder, find the these 9 files, put it in your resource folder,
And You are done.. !!!
#import "SimpleAudioEngine.h" // wherever you want to call in head part of the file.
Step1 call short file.!
[[SimpleAudioEngine sharedEngine] playEffect:#"blast.mp3"];
step2 call background loop.
[[SimpleAudioEngine sharedEngine] playBackgroundMusic:#"background.mp3" loop:YES];
NOTE: There are list of available function http://www.cocos2d-iphone.org/api-ref/0.99.5/interface_simple_audio_engine.html , Its very easy and simple !
Whole implementation will take, 20 minutes max !
Initialize your player in app delegate file and play your background music. Only set one variable in app delegate which checks music play true or false...and enjoy your app without restarting music......
In your code you initialize you player in view did load and init method... that's why you music restart.....just call it only once in app delegate applicationdidfinshLaunching() method....
I followed this tutorial, and included a video player in my app.
But the problem is that i want to hide the controls, and be able to dismiss the video on screen touch.
I tried putting a big transparent button in front of the video that triggers the dismiss function, but with no luck. the video will always be over the button and the function will never be called.
Is there another way of doing it?
ty
**Hi I think AVPlayer is become more suitable to you,You can use it as below and then add subview if you want to play and if you want to stop remove it from super view
** #import"AVFoundation/AVFoundation.h"
**For creating Player List:
NSString *path1 = [[NSBundle mainBundle] pathForResource:#"hello" ofType:#"mp4"];
AVPlayerItem *first = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:path1]];
player= [AVPlayer playerWithPlayerItem:first];
[self.playerView setPlayer:player];
[player play];
** You have to make uiview for playerview in it :
(id)initWithFrame:(CGRect)frame {self = [super initWithFrame:frame];
if (self) {
// Initialization code.
}
return self;
}
+ (Class)layerClass {
return [AVPlayerLayer class];
}
-(AVPlayer*)player {
return [(AVPlayerLayer *)[self layer] player];
}
-(void)setPlayer:(AVPlayer *)player {
[(AVPlayerLayer *)[self layer] setPlayer:player];
}
PlayerViewControll .H
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#interface PlayerView : UIView UILabel *pageNumberLabel;
int pageNumber;
}
#property (nonatomic, retain) AVPlayer *player;
- (id)initWithPageNumber:(int)page;
PlayerView .M
#import "PlayerView.h"
#implementation PlayerView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {}
return self;
}
+ (Class)layerClass {
return [AVPlayerLayer class];
}
- (AVPlayer*)player {
return [(AVPlayerLayer *)[self layer] player];
}
- (void)setPlayer:(AVPlayer *)player {
[(AVPlayerLayer *)[self layer] setPlayer:player];
}
MainViewControll .H
#import <AVFoundation/AVFoundation.h>
#import "PlayerView.h"
#interface MainViewController : UIViewController {
IBOutlet PlayerView *playerView;
NSString *url;
AVPlayer *player;
NSMutableArray *arrIteam;
}
#property(nonatomic,retain) NSMutableArray *arrIteam;
#property (nonatomic, retain) AVPlayer *player;
#property(nonatomic ,retain)IBOutlet PlayerView *playerView;
PlayerView.M
#import "MainViewController.h"
#import <QuartzCore/QuartzCore.h>
#implementation MainViewController
#synthesize player,playerView,arrIteam;
- (void)viewDidLoad {
NSString *path1 = [[NSBundle mainBundle] pathForResource:#"hello" ofType:#"mp4"];
AVPlayerItem *first = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:path1]];
arrIteam = [[NSMutableArray alloc] initWithObjects:first,second, third,fourth,nil];
player=[AVPlayer playerWithPlayerItem:[arrIteam objectAtIndex:i]];
[self.playerView setPlayer:player];
[player play];
[super viewDidLoad];
}
You should use UIGestureRecognizer class. See manual for details. Or read this tutorial.
Use this code.
UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(stopPlayer)];
[self.view addGestureRecognizer:gestureRecognizer];
gestureRecognizer.cancelsTouchesInView = NO;
[gestureRecognizer release];
in view didload;
And in
- (void) stopPlayer
stop the player and release this player from view.
Hope it helps you.
i just found the solution to my problem in another question asked here. after some minor modifications, the code worked as expected. thank you all.