Search code examples
iosxcodeuiscrollviewmp3

IOS: sound in a scrollview


I have this code:

- (void) setAudioScroll{
NSString *path = [NSString stringWithFormat:@"%@/%@",
                  [[NSBundle mainBundle] resourcePath],
                  @"scroll1.mp3"];
NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
soundScroll = [[AVAudioPlayer alloc] initWithContentsOfURL:filePath error:nil];
[soundScroll prepareToPlay]; 

}

- (void) scrollViewDidScroll:(UIScrollView *)scrollView{


    [soundScroll play];
}

Then I want to make a sound when scrollview scroll. but when I scroll it I see that don't work fine because when it call the mp3 sound it stop its scroll for a short time. Can I use a separated thread?


Solution

  • - (void) scrollViewDidScroll:(UIScrollView *)scrollView
    

    Is called many times during a single scroll, at very short time intervals, you don't want to be calling [soundScroll play]; every time this callback occurs, instead use this callback

    - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
    

    so that the sound is played once when the scrolling starts, or either of these

    - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
    - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
    

    if you want the sound the play after the user scrolls. If you want a short sound to be looping continuously through the scroll you can set the AVAudioPlayer numberOfLoops property to a negative value so that it loops indefinately, then stop it when the scrolling stops.