开发者

Play sound when UIScrollView is scrolling

开发者 https://www.devze.com 2022-12-27 11:07 出处:网络
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开发者_如

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

精彩评论

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