AVAudioPlayer sound on iPhone stops looping unexpectedly: How to debug? - iphone

I am implementing a sound effect that plays while a user is dragging a UISlider.
In a previous question, I used AudioServicesPlaySystemSound() but that type of sound can't be halted. I need the sound to halt when the user is not actively dragging the slider but has not released it.
Now I am creating a sound using an AVAudioPlayer object. I initialize it in my View Controller like this:
#interface AudioLatencyViewController : UIViewController <AVAudioPlayerDelegate> {
AVAudioPlayer *player1;
}
#implementation AudioLatencyViewController
#property (nonatomic, retain) AVAudioPlayer *player1;
#synthesize player1;
-(void)viewDidLoad {
[super viewDidLoad];
// the sound file is 1 second long
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"tone1" ofType:#"caf"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
[fileURL release];
self.player1 = newPlayer;;
[newPlayer release];
[self.player1 prepareToPlay];
[self.player1 setDelegate:self];
}
I have two methods to control the sound. The first one plays the sound whenever the slider is being moved. It is connected to the UISlider's Value Changed event in Interface Builder.
-(IBAction)sliderChanged:(id)sender;
{
// only play if previous sound is done. helps with stuttering
if (![self.player1 isPlaying]) {
[self.player1 play];
}
}
The second method halts the sound when the user releases the slider button. It's connected to the UISlider's Touch Up Inside event.
-(IBAction)haltSound;
{
[self.player1 stop];
}
This works when the slider button is moved then released quickly, but if you hold down the button longer than two or three seconds, the sound repeats (good) then breaks up (bad). From then on, the sound won't play again (super bad).
I have tried setting the sound to loop using:
[self.player1 setNumberOfLoops:30];
...but that leads to the app freezing (plus locking up the Simulator).
What can I do to debug this problem?

When a user is holding the UISlider, Value Changed gets called MANY MANY times (any time the user moves just a slight amount). I would use Touch Down instead.
You might want to still try using the loop for this route...
I like the idea of playing a sound while the user is moving the slider though. Let me know how it works out.
deggstand#gmail.com

Related

AudioServicesPlaySystemSound sound not audible when called from IBAction method

I'm having a problem with AudioServicesPlaySystemSound in my iOS app.
I have a method defined to play a system sound. When I call the method from viewDidLoad, I can hear the sound play, but when I call it from a button handler, I do not hear the sound play.
Here's the code from my view controller:
SystemSoundID startSound = 0;
-(void)playStartSound
{
AudioServicesPlaySystemSound(startSound);
}
-(void)viewDidLoad
{
NSURL *urlStart = [[NSBundle mainBundle] URLForResource:#"Beep" withExtension:#"wav"];
AudioServicesCreateSystemSoundID((CFURLRef)urlStart, &startSound);
[self playStartSound];
[super viewDidLoad];
}
- (IBAction)start:(id)sender
{
[self playStartSound];
}
The IBAction method is associated with a button. When I select the button, the playStartSound method gets called, but the sound is not audible.
The system sound is not disposed of with AudioServicesDisposeSystemSoundID until the dealloc method is called.
I've tried calling AudioServicesCreateSystemSoundID from within playStartSound, but it didn't make any difference.
The app also uses AV Foundation, Media Player, Core Media, Core Video, and Core Location. I'm wondering if one of these might be interfering with AudioToolbox?
UPDATE: I just put together a simple app that just contains the above code and a button and the sound plays just fine when I select the button.
So then I removed all the video capture code from my controller and now the audio plays fine.
This was not working because I had an active video capture session in my application.
AudioServicesPlaySystemSound will not play when there is an active video capture session.
NSString *soundPath = [[NSBundle mainBundle] pathForResource:#"7777" ofType:#"mp3"];
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)([NSURL fileURLWithPath: soundPath]), &soundID);
AudioServicesPlaySystemSound (soundID);
Hey try like that it will play

AVAudioPlayer - Muting button

I have searched for this answer and have not found it.
I have music that plays in the background when my iPhone app is launched. But I want a button so that users can mute the music. There are sound effects within the app also so sliding the mute button on the side of the device won't cut it.
This is the current code I have for the AVAudioPlayer.
- (void)viewDidLoad{
#if TARGET_IPHONE_SIMULATOR
//here code for use when execute in simulator
#else
//in real iphone
NSString *path = [[NSBundle mainBundle] pathForResource:#"FUNKYMUSIC" ofType:#"mp3"];
AVAudioPlayer *TheAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
TheAudio.delegate = self;
[TheAudio play];
TheAudio.numberOfLoops = -1;
#endif
}
Can anyone help me out the code needed for a simple button to simply stop the music and start it again.
Thanks in advanced.
Put this code in the viewcontroller.h file:
-(IBAction) btnStop:(id)sender;
Put this code in the viewcontroller.m file:
-(IBAction) btnStop:(id)sender {
[TheAudio stop];
//Whatever else you want to do when the audio is stopped
}
In the Interface builder, connect a button to this action, so when it is clicked this action will be called.
That should make the music stop.
Its easier to display code in an answer:
-(IBAction) playerPlay:(id)sender {
if([player isPlaying]) {
[player stop];
}
if(![player isPlaying]) {
[player play];
}
}
I'll explain:
The [player isPlaying] method checks to see if the audio is playing. If the audio is playing, everything in the brackets is executed (in this situation, the audio stops playing).
Because of the "!" in ![player isPlaying], the method is made the opposite of what it usually is. This means that if the player is NOT playing, everything in the brackets is executed (in this situation, the audio starts playing).
All of this is enclosed in the IBAction, so that it is executed when the button is clicked.
For future reference, the correct format for an If statement in Objective-C is:
if(thing to check for) {
things that happen if the thing that is check for is correct;
}
The word "then" is never actually used, but it is the same thing and whatever is in the brackets.
Hope this helps!

Touch Drag Inside triggers sound repeatedly & Touch Up Inside doesn't work

I'm trying to do an app where a short sound sample is supposed to be played while the person using the app is dragging his/her finger(s) across the screen. When the finger(s) are lifted away from the screen - the sound will stop.
This is the function that triggers the sound:
-(IBAction) playSound:(id)sender{
NSString *soundPath = [[NSBundle mainBundle]pathForResource:#"sound" ofType:#"wav"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundPath];
newPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:nil];
newPlayer.numberOfLoops = -1;
[newPlayer play];
}
This is the function that stops the sound:
-(IBAction) stopSound{
if ([newPlayer isPlaying]) {
[newPlayer stop];
}
[newPlayer release];
}
I first started out using the Touch Down event, which looped the sound seamlessly. At this point the stopSound worked together with the "Touch Up Inside" event.
The point, as I said, is the sound is supposed to be generated when the user drags his/her finger(s) across the screen. But when I tried to the tie the playSound function to the "Touch Drag Inside" the sound loops repeatedly over itself, instead of one at the time, making it hell to use. The stopSound function doesn't work after i changed to the Drag Event.
I tried to use NSTimer to create some kind of way to handle the loops, but without any success.
My advice would be to create to generate a method that loops your audio clip (whatever duration, overlap, pausing, etc you want). Setup the method so that when you call it to play, it plays the way you want it to indefinitely.
The method might look like:
-(void) beginOrContinuePlayingAudioLoop:(BOOL)shouldPlay {
//if touchesMoved called, shouldPlay will be YES
//if touchesEnded called, shouldPlay will be NO
if (shouldPlay == NO) {
//cease playing
currentlyPlaying = NO;
}
if (currentlyPlaying == YES) {
return;
} else {
//begin playing audio
currentlyPlaying = YES;
}
}
In your ViewController class, define a BOOL (currentlyPlaying) that indicates whether the audio loop is currently playing.
As opposed to using canned IBAction gesture recognizers, consider overriding the more generic touch responder calls, touchesMoved and touchesEnded on your view.
In touchesMoved, set your VC's BOOL to YES and then fire your audio looping method to start playing. The "playing" method should always check and see if the audio is already playing, and only start playing
Also place a check in your method that returns/exits your method when the audio loop is already playing, this will avoid overlapping.
In touchesEnded, kill your audio via whatever method you choose, and reset the BOOL to NO.

Help stopping audio using AVAudioPlayer

Alright I have two problems. I'm using AVAudioPlayer to play a simple audio file in .caf format. What I'm trying to do is have a play and pause button. Here is a sample of a simple IBAction to play the audio from a button.
- (IBAction) clear {
NSString *path = [[NSBundle mainBundle] pathForResource:#"clear" ofType:#"caf"];
AVAudioPlayer* myAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
myAudio.delegate = self;
myAudio.volume = 1.0;
myAudio.numberOfLoops = 0;
[myAudio play];
}
So when I go ahead and create another IBAction with the method...
- (IBAction) stopaudio {
[myAudio stop];
audioPlayer.currentTime = 0;
}
I compile and xcode tells me that myAudio in the stopaudio IBAction is not defined. How do I fix it so I'm able to access myAudio in another IBAction?
My Second question is that I'm using NavigationController to setup a TableView, when I make a selection it takes me to a UIView with a back button to go back to the TableView. What I'm trying to do is to kill any audio that I have playing in the UIView when I go back to the TableView. The code above is part of the code that I'm going to have in the UIView.
Also one quick question. Lets say I have an audio file that is 1 minute long. Clicking play again will overlap a new instance of that audio before the old instance is done playing. How can I check to see if myAudio is playing and not allow it to be played again until myAudio is finished playing?
Thank You!
First of all, you should read the documentation. It will remove almost all of your questions. Nevertheless, to have access to your instance of AVAudioPlayer from all methods of your class, you should define it in your .h file. To stop your player on returning to the previous screen, call [myAudio stop] in your viewWillDisappear:(BOOL)animated method. About your last question. If you define myAudio in your .h file, you will be able to check if it is playing now. smth like
- (IBAction) clear {
if(![myAudio isPlaying]){
[myAudio play];
}
}

AVAudioPlayer is not rentrant correct?

It appears that AVAudioPlayer is not reentent. So in the following would soundfx play to completion, delay 1 second, then play again, rather then the 1 second delay - and resultant overlapping playback I desire:
// ...
AVAudioPlayer* soundfx = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];
(void) makeSomeNoise {
[soundfx play];
sleep(1);
[soundfx play];
}
Must I then resort to NSOperation - threading - to achieve my goal of overlapping playback?
Note: I am using IMA4/ADPCM format which is apparently the correct format for layered sound playback.
Cheers,
Doug
It's not that AVAudioPlayer is not reentrant. It is that AVAudioPlayer starts to play your sound after the runloop has ended, and not in your makeSomeNoise function. If you want to play your sound with a one second delay, you can do this:
(void) makeSomeNoise {
[soundfx play];
[soundfx performSelector:play withObject: nil afterDelay:1.0];
}