Play/Pause with the same button [AVAudioPlayer] - iphone

How can I play a sound with an IBAction by pressing on a UIbutton once and pause it by pressing the button again using AVAudioPlayer? Also I want to change the state of that UIButton when the sound is playing and when it's not.
Here's my code:
- (IBAction)Beat
{
if ([Media2 isPlaying])
{
[Media2 pause];
[Button17 setSelected:NO];
}
else
{
Path = [[NSBundle mainBundle] pathForResource:#"Beat" ofType:#"mp3"];
AVAudioPlayer *Media2 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:Path] error:NULL];
[Media2 setDelegate:self];
[Media2 play];
[Button17 setSelected:YES];
}
}

Here's is simple method using BOOL Variable.
Set playing = NO in viewDidLoad.
-(void)PlayStop{
if (playing==NO) {
// Init audio with playback capability
[play setBackgroundImage:[UIImage imageNamed:#"hmpause.png"] forState:UIControlStateNormal];
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:______ error:&err];
[audioPlayer prepareToPlay];
audioPlayer.delegate=self;
[audioPlayer play];
playing=YES;
}
else if(playing==YES){
[play setBackgroundImage:[UIImage imageNamed:#"Audioplay.png"] forState:UIControlStateNormal];
[audioPlayer pause];
playing=NO;
}
}

Keep your audioPlayer instance ready to play using the below method.
/*
Prepares the audio file to play.
*/
-(void) initWithAudioPath:(NSString *) audioPath {
// Converts the sound's file path to an NSURL object
NSURL *audioPathURL = [[NSURL alloc] initFileURLWithPath:audioPath];
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioPathURL error:nil];
audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
[audioPathURL release];
}
-(void) pausePlaybackForPlayer:(AVAudioPlayer *) player {
[player pause];
}
-(void) startPlaybackForPlayer:(AVAudioPlayer *) player {
if (![player play]) {
NSLog(#"Could not play %#\n", player.url);
}
}
- (IBAction)Beat {
if (audioPlayer.playing == NO) {
// Audio player is not playing.
// Set the button title here to "stop"...
[self startPlaybackForPlayer:audioPlayer];
}else {
// Audio player is playing.
// Set the button title here to "play"...
[self pausePlaybackForPlayer:audioPlayer];
}
}

Related

Can AVFoundation play Audio and get Details of it On the IOS 5.0 Simulator?

Can the Above be Done using only AVFoundation.framework?
i Tried doing a few experiment but i can't really get it to work
(sorry newbie here please do tell me where to put the codes at Example: ViewController or the MainView)
These are my code,(UI Components are inside as i'm do not want use interface builder)
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
NSError *error;
buttonPlay = [[UILabel alloc] initWithFrame:CGRectMake(0, 350, 100, 50)];
buttonPlay.text = #"Play";
// Get the file path to the song to play.
NSString* path;
NSURL* url;
path = [[NSBundle mainBundle] pathForResource:#"Bring_Me_To_Life.mp3" ofType:nil];
url = [NSURL fileURLWithPath:path];
NSData *_objectData = [NSData dataWithContentsOfURL:url];
//Initialize the AVAudioPlayer.
audioPlayer = [[AVAudioPlayer alloc] initWithData:_objectData error:&error];
// Preloads the buffer and prepares the audio for playing.
audioPlayer.numberOfLoops = 0;
audioPlayer.volume = 1.0f;
[audioPlayer prepareToPlay];
if (audioPlayer == nil)
NSLog(#"%#", [error description]);
else
[audioPlayer play];
[self addSubview:buttonPlay];
}
return self;
}
-(void)touchesBegan:(CGPoint)location{
if(CGRectContainsPoint(buttonPlay.frame, location)){
NSLog(#"Dec from Chl %f",[audioPlayer peakPowerForChannel:0]);
NSLog(#"Length of Clip %f",[audioPlayer duration]);
}
}
try this
audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];

AVAudioPlayer - Pause button

My previous code was
- (void) playaudio: (id) sender
{
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Theme"
ofType:#"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
self.audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:fileURL error:nil];
self.audioPlayer.currentTime = 0;
[self.audioPlayer play];
}
- (void)pause: (id)sender
{
[audioPlayer pause];
}
- (void)stop: (id)sender
{
[audioPlayer stop];
}
In the above code pause button was acting as stop button rather than pause where it was supposed to resume the audio file.
Now i have added simple statements to my code it is working to some extent but still not upto my expectations.
What happening now is when you play audio file and click on pause button nothing happens but when you click on the stop button it stops playing audio file and then when you press the pause button it resumes the audio file from where it was stopped by pressing stop button. Why is that when you press stop buttons only then pause button functions but not before that. I don't get this why?
Any ideas why this is happening
- (void)pause: (id)sender
{
[audioPlayer pause];
[audioPlayer prepareToPlay];
[audioPlayer play];
}
- (void) stop: (id) sender
{
[audioPlayer stop];
}
If anyone have any ideas that why this is happening. Will appreciate help.
Thanks in advance.
You shouldn't be recreating the audio file every time you play it. Here is how you could do this:
- (void) playaudio: (id) sender
{
if(self.audioPlayer == nil) {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Theme"
ofType:#"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
self.audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:fileURL error:nil];
self.audioPlayer.currentTime = 0; //this could be outside the if if you want it to start over when they hit play
}
[self.audioPlayer play];
}
- (void)pause: (id)sender
{
if([audioPlayer isPlaying]){
[audioPlayer pause];
} else {
[audioPlayer play];
}
}
- (void)stop: (id)sender
{
[audioPlayer stop];
}

Cocoa audio issues

I have 2 buttons, 1 turns to the next page and should play a sound at the same time but the sound doesn't seems to be working, I need your help on this please.
I have 4 pages and in each page there is a play button that play or stop the audio, but if I press play and press next to the next page, the audio will keep playing, how do I do so that if I press the next button, it will stop the music automatically.
Thanks for your help, find below the code.
- (IBAction)next {
// This part plays the next page turn noise
NSURL *this = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/next.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:this error:&error];
[audioPlayer setDelegate:self];
audioPlayer.numberOfLoops = 0;
[audioPlayer play];
// This part takes us to the next view
Rabbana2 *rab = [[Rabbana2 alloc] initWithNibName:#"Rabbana2" bundle:nil];
[UIView beginAnimations:#"flipView" context:Nil];
[UIView setAnimationDuration:2];
[UIView setAnimationCurve:UIViewAnimationOptionCurveEaseInOut];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES];
[self.view addSubview:rab.view];
[UIView commitAnimations];
}
// This button plays the audio
- (IBAction)play {
if(clicked == 0){
clicked = 1;
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/rabbana1.wav", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[audioPlayer setDelegate:self];
audioPlayer.numberOfLoops = 0;
[audioPlayer play];
[start setImage:[UIImage imageNamed:#"Sstop.png"] forState:UIControlStateNormal];
}
else{
[audioPlayer release];
clicked = 0;
[start setImage:[UIImage imageNamed:#"Pplay.png"] forState:UIControlStateNormal];
}
}
//If user does not do anything by the end of the sound set the button to start
- (void) audioPlayerDidFinishPlaying: (AVAudioPlayer *) player
successfully: (BOOL) flag {
if (flag==YES) {
clicked = 0;
[start setImage:[UIImage imageNamed:#"Pplay.png"] forState:UIControlStateNormal];
}
}
In your method which handles the page turn, you need to stop the current playing sound by using [audioPlayer stop] if it is playing

can I stop the play back using my app

I am using AudioPlayer to stop all playbacks , as code is given
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/audiofile.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
if (audioPlayer == nil)
NSLog([error description]);
else
[audioPlayer play];
But i can stop all play back using this but can not again play stopped play backs.How can I do this please help
You can easily play pause stop your AVAudioPlayer with these three methods:
- (void)pause
- (void)stop
- (BOOL)play //Returns YES on success, or NO on error.
If you pause, you can then play to resume from where you paused.
Hope this helps, i really don't see where your problem is!
in the code you gave, you are not pausing, you are just playing it with numberOfLoops negative.
You should have a method to start your music like this:
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/audiofile.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;//play once
if (audioPlayer == nil)
NSLog([error description]);
else
[audioPlayer prepareToPlay];
[audioPlayer play];
And another for pausing:
[audioPlayer pause];
And another for resuming:
[audioPlayer play];
To toggle iPod music when the app starts and exits override these two methods:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
MPMusicPlayerController *musicPlayer;
MPMusicPlaybackState playbackState = [musicPlayer playbackState];
if (playbackState == MPMusicPlaybackStatePlaying) { //simple verification
[musicPlayer pause];
}
}
- (void)applicationWillResignActive:(UIApplication *)application
if (playbackState == MPMusicPlaybackStateStopped || playbackState == MPMusicPlaybackStatePaused) {//simple verification
[musicPlayer play];
}
}
Hope it finally suits your needs!

stopping an AVAudioPlayer

here is my code
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"95" ofType:#"wav"];
NSError *activationError = nil;
NSError *audioPlayerInitError = nil;
[[AVAudioSession sharedInstance] setActive: YES error:&activationError];
NSURL *newURL = [NSURL fileURLWithPath:soundFilePath];
musicPlayer1 = [[AVAudioPlayer alloc] initWithContentsOfURL:newURL error:&audioPlayerInitError];
if (musicPlayer1) {
[musicPlayer1 stop];
[musicPlayer1 release];
musicPlayer1 = nil;
}
else {
[musicPlayer1 prepareToPlay];
[musicPlayer1 setVolume:.8];
[musicPlayer1 setNumberOfLoops:-1]; // -1 means play indefintely
[musicPlayer1 setDelegate: self];
[musicPlayer1 play];
}
}
I am rying to start and stop the AVAudioPlay with the same button (musicPlayer1 is in the header). Now when i touch the button it does not play anything. Help please?
You're creating a new instance of AVAudioPlayer each time. You need to hold onto the reference to the object somewhere, and refer back to that. Add a field to your view controller class:
#private AVAudioPlayer *currentAudio;
And then in this method, make the following changes:
if (currentAudio) {
[currentAudio stop];
[currentAudio release];
currentAudio = nil;
} else {
// what you already have goes here
}