开发者

Play sound when UIScrollView is scrolling

I have a scroll view that can be scrolled to the sides (only left and right, not up and down). I want to play a short sound (less than a second) whenever the scroll view is moved X pixels to e开发者_如何学Cither side.

How can this be done? Code samples will be greatly appreciated...

Thanks,


Here is the code I used:

I added the SoundEffect.h and SoundEffect.m files to my project (you can find them online). Then, I created a sound effect instance:

SoundEffect *soundEffect;

Then, I setup my UIViewController as the delegate of my UIScrollView by adding <UIScrollViewDelegate> to the .h file of the view controller and setting the relevant outlet of the UIScrollView.

In the -(void)viewDidLoad method, I initialized my sound effect:

NSBundle *mainBundle = [NSBundle mainBundle];
soundEffect = [[SoundEffect alloc] initWithContentsOfFile:[mainBundle pathForResource:@"Tik" ofType:@"wav"]];

And then, I implemented these two methods:

#pragma mark -
#pragma mark Scroll View Delegate Methods

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    lastScrollPosition = scrollView.contentOffset.x / 55;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{   
    if ((int)(scrollView.contentOffset.x / 55) != lastScrollPosition1)
    {
        lastScrollPosition1 = scrollView.contentOffset.x / 55;
        [soundEffect1 play];
    }
}

I needed the sound effect to fire every 55 pixels to either direction, but you can change this to a constant value that fits your needs. It works great for me, and hopefully, it will help others as well...


Try assigning your viewController as the scroll view's delegate, and adding a -scrollViewWillBeginDragging: method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜