【问题标题】:Touch Drag Inside triggers sound repeatedly & Touch Up Inside doesn't workTouch Drag Inside 反复触发声音 & Touch Up Inside 不起作用
【发布时间】:2011-10-04 15:38:46
【问题描述】:

我正在尝试做一个应用程序,当使用该应用程序的人在屏幕上拖动他/她的手指时,应该播放一个简短的声音样本。当手指离开屏幕时 - 声音将停止。

这是触发声音的函数:

-(IBAction) playSound:(id)sender{

NSString *soundPath = [[NSBundle mainBundle]pathForResource:@"sound" ofType:@"wav"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundPath];

newPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:nil];
newPlayer.numberOfLoops = -1;
[newPlayer play];   
}

这是停止声音的功能:

-(IBAction) stopSound{
if ([newPlayer isPlaying]) {
    [newPlayer stop];
}
[newPlayer release];
}

我最开始使用的是 Touch Down 事件,它可以无缝地循环播放声音。此时,stopSound 与“Touch Up Inside”事件协同工作。

正如我所说,关键是当用户在屏幕上拖动他/她的手指时应该会产生声音。但是,当我尝试将 playSound 功能与“Touch Drag Inside”联系起来时,声音会在自身上反复循环,而不是一次循环,这让它很难使用。更改为拖动事件后,stopSound 功能不起作用。

我尝试使用 NSTimer 创建某种方式来处理循环,但没有任何成功。

【问题讨论】:

    标签: iphone objective-c audio touch drag


    【解决方案1】:

    我的建议是创建一种方法来循环播放您的音频剪辑(无论您想要什么持续时间、重叠、暂停等)。设置方法,以便当您调用它播放时,它会无限期地按照您想要的方式播放。

    该方法可能如下所示:

    -(void) beginOrContinuePlayingAudioLoop:(BOOL)shouldPlay {
    
     //if touchesMoved called, shouldPlay will be YES
     //if touchesEnded called, shouldPlay will be NO
    
     if (shouldPlay == NO) {
     //cease playing
     currentlyPlaying = NO;
     }
    
    if (currentlyPlaying == YES) {
    
    return;
    
    } else {
    
    //begin playing audio
    currentlyPlaying = YES;
    
     }
    }
    

    在您的 ViewController 类中,定义一个 BOOL (currentlyPlaying) 来指示音频循环当前是否正在播放。

    与使用预设的 IBAction 手势识别器相反,请考虑在您的视图上覆盖更通用的触摸响应器调用、touchesMoved 和 touchesEnded。

    在 touchesMoved 中,将 VC 的 BOOL 设置为 YES,然后触发音频循环方法开始播放。 “播放”方法应该总是检查音频是否已经在播放,然后才开始播放

    同时在你的方法中放置一个检查,当音频循环已经播放时返回/退出你的方法,这将避免重叠。

    在 touchesEnded 中,通过您选择的任何方法终止您的音频,并将 BOOL 重置为 NO。

    【讨论】:

    • 感谢您的回答,并为我的迟到表示歉意。您的代码为我指明了正确的方向;我最终将我的 playsound 包装在一个 if 语句中,检查 mySound 是否正在播放。 if (![mySound isPlaying]{[mySound play];}
    猜你喜欢
    • 2011-04-23
    • 2012-06-23
    • 2012-08-31
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多