views:

153

answers:

3

Hey,

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 either side.

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

Thanks,

A: 

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

Ben Gottlieb
But that will only plat the sound once, won't it? I want the sound to start whenever the scrollview moves X pixels to either side. I was thinking about initializing a timer in this method that will check every 0.1 second or so, whether the view crossed more than X pixels and stop that timer in the relevant delegate method. But I'm wondering if there's a better way to do this...
Chonch
You want the sound to repeat as the view is dragged? You could use scrollViewDidScroll:.
Ben Gottlieb
Thanks. I tried using the scrollViewDidScroll: method and it works great...
Chonch
A: 

Hi Chonch, i am also trying the same. It plays sound, but only in 1 direction from left to right. I am not able to play both sides when scroll happens. Can you share your code.

kumar
Hey kumar. I added the code I used. Hopefully, it will help you. If it doesn't work, let me know... Good luck!
Chonch
A: 

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...

Chonch