2011-10-04 56 views
0

我正试图做一个应用程序,在使用应用程序的人拖动他/她的手指时应该播放短声音样本,穿过屏幕。当手指离开屏幕时 - 声音将停止。触摸拖动里面反复触发声音和触摸里面不起作用

这是触发声音的功能:

-(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]; 
} 

我第一次开始使用的触摸按下事件,环声音无缝连接。此时,stopSound与“Touch Up Inside”事件一起工作。

正如我所说的,声音是在用户在屏幕上拖动他/她的手指时产生的声音。但是,当我试图将playSound功能与“Touch Drag Inside”绑定时,声音在其自身上反复循环播放,而不是在当时使用,使其无法使用。在我改变为拖动事件后,stopSound函数不起作用。

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

你们有什么好主意吗? 我是初学者,谈到Objective-C,iPhone的发展& XCode - 对我来说很裸露。

回答

0

我的建议是创建一个方法来循环你的音频片段(无论持续时间,重叠,暂停等你想要的)。设置该方法,以便在您打电话时播放它的方式无限期地播放。

的方法可能如下:

-(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。

+0

谢谢你的回答,并且为我的这个迟到而道歉。 你的代码指出了我的正确方向;我最后把我的歌曲包装在if语句中,检查mySound是否正在播放。 if(![mySound isPlaying] {[mySound play];} – user978679