Play sound when UIScrollView is scrolling

喜夏-厌秋 提交于 2020-01-12 10:52:50

问题


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,


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/2682623/play-sound-when-uiscrollview-is-scrolling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!