views:

681

answers:

1

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?

A: 

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.

[email protected]