Jacob Gustafson
Jacob Gustafson

Reputation: 1

How do I stop a sound in AVFoundation?

I have done a iPhone app where I press a UIButton and a sound plays. but when I press it again I want it to stop. I have many sounds, but I only want this sound to stop when pressing it twice.

Here is the code I use!

-(IBAction)pushBeat {   
    NSString *path =[[NSBundle mainBundle]
    pathForResource:@"beat1" ofType:@"mp3"];
    AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
    theAudio.delegate = self;
    [theAudio play];    
}

Upvotes: 0

Views: 802

Answers (2)

CarlosBermudez
CarlosBermudez

Reputation: 41

Maybe it is not going to help you, but it can help for other.

What you should do is a class variable In the class.h, make a AVAudioPlayer variable:

{
   AVAudioPlayer *actualAudioPlayer_;
}
@property(nonatomic, retain) AVAudioPlayer *actualAudioPlayer;

In the class.m, make his sythesize and his dealloc and later this is the method changed:

-(IBAction)pushBeat {   
    NSString *path =[[NSBundle mainBundle]
    pathForResource:@"beat1" ofType:@"mp3"];

    [self.actualAudioPlayer stop]; //NEW

    AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];

    self.actualAudioPlayer = theAudio; //NEW
    [sel.actualAudioPlayer play];  //NEW
    [theAudio release]; //NEW


}

Hope this helps someone!!

Upvotes: 1

Geoffrey
Geoffrey

Reputation: 11354

I dont know much about xcode, so this may be wrong, let me know if so.

It seems that "theAudio" should be made a class member, not a local member to the function, in C++ you would do this (again, because I dont know xcode this is pseudo code).

class MyClass {
public:
  MyClass();
  ~MyClass();
  void pushBeat();
private:
  AVAudioPlayer* theAudio;
}

MyClass::MyClass() {
  theAudio = NULL;
}

MyClass::~MyClass() {
  delete theAudio;
}

void pushBeat() {
  if (!theAudio) {
    theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
    theAudio.delegate = self;
  }

  if (!theAudio.playing)
    [theAudio play];
  else
    [theAudio stop];
}

Upvotes: 0

Related Questions