iPhone SDK: How do you stop video playback with code? - iphone

In my app, I play a video using this simple code:
NSBundle *bundle = [NSBundle mainBundle];
NSString *moviePath = [bundle pathForResource:#"video" ofType:#"mp4"];
NSURL *movieURL = [[NSURL fileURLWithPath:moviePath] retain];
MPMoviePlayerController *theMovie = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
theMovie.movieControlMode = MPMovieControlModeHidden;
[theMovie play];
I'd like to know how to stop the video with code, I have tried [theMovie stop]; but this doesn't work, and an error is given, 'theMovie' undeclared (first use in this function) Which is understandable as the "theMovie" is only declared in the method that plays it. Has anyone got any ideas on how to stop it with out having to show the built in movie player controls? Any Help appreciated.

If you are creating that video in some method with that code and calling stop in some other method, the error shows up because theMovie only exists in the former method. You would need to set up an ivar or #property.
Check out this question.
EDIT:
A sample code (not tested):
#interface Foo : UIViewController {
MPMoviePlayerController *_theMovie;
}
#property (nonatomic, retain) MPMoviePlayerController *theMovie;
- (void) creationMethod;
- (void) playMethod;
- (void) stopMethod;
#end
#implementation Foo
#synthesize theMovie = _theMovie;
- (void) creationMethod {
NSString *moviePath = [[NSBundle mainBundle] pathForResource:#"video" ofType:#"mp4"];
NSURL *movieURL = [NSURL fileURLWithPath:moviePath]; // retain not necessary
self.theMovie = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
self.theMovie.movieControlMode = MPMovieControlModeHidden;
}
- (void) playMethod {
[self.theMovie play];
}
- (void) stopMethod {
[self.theMovie stop];
}
- (void) dealloc {
[_theMovie release];
}
#end
You would call the creationMethod somewhere to create your movie player. This is just an example of how a player could be placed in a property so you could use it across many methods but not necessarily a best practice. You could/should take a look at the iPhone documentation on declared properties.
I must note that I haven't used the MPMoviePlayerController class, though, so exact code might be different.

Related

Objective-C background music

I want to know how to add background music to my app.
My code so far:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"Jaunty Gumption" ofType:#"mp3"]];
AVAudioPlayer *backgroundMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
backgroundMusic.numberOfLoops = -1;
[backgroundMusic play];
}
But when I launch the app nothing happens and I don't know why.
I have included the AVFoundation an AudioToolbox frameworks.
Any help would be appreciated. :)
Thanks Matis
ARC is destroying your audio player before it gets any chance to output audio. When an audio player is about to be destroyed, it stops playing audio. Assign it to a strong property instead of a local variable, like so:
#interface MyClass : UIViewController
#property(nonatomic, strong) AVAudioPlayer *backgroundMusic;
#end
#implementation MyClass
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *musicFile = [[NSBundle mainBundle] URLForResource:#"Jaunty Gumption"
withExtension:#"mp3"];
self.backgroundMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile
error:nil];
self.backgroundMusic.numberOfLoops = -1;
[self.backgroundMusic play];
}
#end
Doing this will keep the audio player alive at least as long as the view controller.

How to auto play music as soon as my app starts?

I need some help with my app I have recently started. I am a very big starter to coding so please do help me, it'll mean a lot. I need a piece of music to play as soon as the user enters my app, i have followed other youtube tutorials but they only work for the older Xcode versions, so please help thank you so much.
How about putting it in you application didFinishLaunching but be sure to instantiate it in you .h and .m.
Something like this should do your problem:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
resourcePath = [resourcePath stringByAppendingString:#"/YOURMUSICNAME.wav"];
NSLog(#"Path to play: %#", resourcePath);
NSError* err;
//Initialize our player pointing to the path to our resource
player = [[AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath:resourcePath] error:&err];
if( err ){
//bail!
NSLog(#"Failed with reason: %#", [err localizedDescription]);
}
else{
//set our delegate and begin playback
player.delegate = self;
[player play];
player.numberOfLoops = -1;
player.currentTime = 0;
player.volume = 1.0;
}
}
Then if you want to stop it:
[player stop];
or pause it :
[player pause];
and also import it in your header file:
#import <AVFoundation/AVFoundation.h>
EDIT:
You should to ofcourse declare it in your header, then synthesize it.
//.h and add the bold part:
#interface ViewController : UIViewController <AVAudioPlayerDelegate> {
AVAudioPlayer *player;
}
#property (nonatomic, retain) AVAudioPlayer *player;
//.m
#synthesize player;
You can use the AVAudioPlayer. It pretty straight forward to use:
NSURL *path = [[NSURL alloc] initFileURLWithPath:[DataPersister getQualifiedPathForFileInDirectory:DataPersisterPathBundle fileName:#"music.mp3"]];
NSError *outError;
AVAudioPlayer *musicSound = [[AVAudioPlayer alloc] initWithContentsOfURL:path error:&outError];
[musicSound play];
[path release];
Remember to import
#import <AVFoundation/AVFoundation.h>
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/MUSIC.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
[audioPlayer play];
audioPlayer.volume = 1.0;
audioPlayer.currentTime = 2;
Use this at - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions method will play music for sure
Happy Coding ;)

iOS - How to stop background music when changing views

How to stop background music when changing views? I have no clue. If i press a button which takes me to a new view, there is new background music. But the old background music (which goes in an infinite loop) keeps on going. Please help! also sample some code please, here is mine:
- (void)viewDidLoad {
NSString *path = [[NSBundle mainBundle] pathForResource:#"MathMusic2" ofType:#"wav"];
AVAudioPlayer* theAudio= [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
theAudio.numberOfLoops = -1;
[super viewDidLoad];
}
I just need to know how to make the background music from the new view stop playing. And vice versa when i press the back button from the new view
Create a property for the AVAudioPlayer *theAudio so you can access the audioPlayer from any point in your class.
Header file of viewController
...
AVAudioPlayer *theAudio;
...
#property (nonatomic, retain) AVAudioPlayer *theAudio;
Implentation file of viewController
...
#synthesize theAudio;
...
- (void)viewDidLoad {
NSString *path = [[NSBundle mainBundle] pathForResource:#"MathMusic2" ofType:#"wav"];
self.theAudio= [[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]] autorelease];
theAudio.delegate = self;
[theAudio play];
theAudio.numberOfLoops = -1;
[super viewDidLoad];
}
If viewWillDisappear is called you can then just stop the audio with
- (void)viewWillDisappear
{
[theAudio stop];
}
it gaves errors in here :
"theAudio.delegate = self;" as something like assigning to id...
its yellow anyway..
still when i change view and go to another class music not stoping....

Adjust AVPlayer Frame Rate During Playback [duplicate]

I'm wondering if it's possible to change the video playback speed in an iphone application. we want users to yell in the microphone to speed up the playback and get to the end.
You have to use setCurrentPlaybackRate:
There is a rate property for the AVPlayer.
If you take the example from Apple called "avPlayerDemo" in the resource section, you then simply have to set the mplayer.rate. It worked for me, I created a new slider in the xib files, implemented that slider in the AVPlayerDemoPlaybackViewController and simply set mPlayer.rate to the slider value.
What about the MPMoviePlayerController?
setCurrentPlaybackRate
Here's some code which does not work at that spot
-(IBAction)abspielen:(id)sender
{
NSString *titleOfButton = [sender titleForState:UIControlStateNormal];
NSBundle *bundle = [NSBundle mainBundle];
NSString *moviePath = [bundle pathForResource:titleOfButton ofType:#"mov"];
NSURL *movieURL = [ NSURL fileURLWithPath:moviePath];
MPMoviePlayerController *themovie = [[MPMoviePlayerController alloc]initWithContentURL: movieURL];
[themovie play];
[themovie setCurrentPlaybackRate:2.f];
[themovie release];
MPMoviePlayerViewController *moviePlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:movieURL];
[self presentMoviePlayerViewControllerAnimated:moviePlayer];
[moviePlayer release];
}

Bug in AVAudioPlayer class?

I'll keep it short and sweet - I'm building an application just for practice before I buy myself the iPhone Developer Program.
I'm experimenting with the AVFoundation.framework and I keep running into a bug which will only let me play the first sound I initialize in my code. Do you think any of you could help me out? Thanks in advance!! :)
view controller
-(IBAction)play {
if (segments.selectedSegmentIndex == 0) {
NSLog(#"Segment = 0");
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle pathForResource:#"meow" ofType:#"wav"];
if (path != nil) {
NSURL *url = [NSURL fileURLWithPath:path];
AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:NULL];
[player prepareToPlay];
[player play];
}
}
else if (segments.selectedSegmentIndex == 1) {
NSLog(#"Segment = 1");
NSBundle *bundle = [NSBundle mainBundle];
NSString *path2 = [bundle pathForResource:#"meowloud" ofType:#"wav"];
if (path2 != nil) {
NSURL *url2 = [NSURL fileURLWithPath:path2];
AVAudioPlayer *player2 = [[AVAudioPlayer alloc]initWithContentsOfURL:url2 error:NULL];
[player2 prepareToPlay];
[player2 play];
// [player2 release];
}
}
text1.textColor = [UIColor clearColor];
text2.textColor = [UIColor clearColor];
text3.textColor = [UIColor clearColor];
text4.textColor = [UIColor clearColor];
}
When this code gets executed, only the meow.wav is executed, no matter which segment is selected.
Your code has a couple of memory leaks. You allocate instances of AVAudioPlayer in your play method, but you never release those instances. See Cocoa's memory management qguidelines for details. Since the AVAudioPlayer instances need to remain in memory to play, the easiest solution is to add a member variable to your viewController class and set it up as a retain property.
For the sake of Don't Repeat Yourself (DRY), I would also suggest adding a method which encapsulates all of the code needed to play a single wav file.
Here is how I would write this view controller:
MyViewController.h
#interface MyViewController : UIViewController
{
AVAudioPlayer *player;
}
#property(nonatomic, retain) AVAudioPlayer *player;
- (void)playWavFile:(NSString *)fileName;
- (IBAction)play;
#end
MyViewController.m
#synthesize player;
- (void)dealloc {
[player release];
}
- (void)playWavFile:(NSString *)fileName {
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle pathForResource:fileName ofType:#"wav"];
if (path != nil) {
AVAudioPlayer *newPlayer;
NSURL *url = [NSURL fileURLWithPath:path];
newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url
error:NULL];
[self setPlayer:newPlayer];
[newPlayer release];
[newPlayer prepareToPlay];
[newPlayer play];
}
}
- (IBAction)play {
if (segments.selectedSegmentIndex == 0) {
[self playWavFile:#"meow"];
}
else if (segments.selectedSegmentIndex == 1) {
[self playWavFile:#"meowloud"];
}
}