2014-04-04 32 views
-1

我做了一個應用程序,與基本上是愚蠢的鳥克隆。當我觸摸屏幕時,我需要知道如何發出聲音。我嘗試使用按鈕,但聲音只會作爲觸摸按鈕,而不是整個屏幕播放。當我觸摸按鈕時,鳥剛掉下來。我知道我可能不得不使用TouchBegan,但是我使用哪些代碼以及我在哪裏放置它們?越詳細越好,因爲我是一個巨大的新手。謝謝!Xcode5如何在每次觸摸屏幕時添加聲音效果?

+0

調查UITapGestureRecognizer。一個可以添加到整個視圖中,並且只要您觸摸屏幕就會調用其操作方法。 – rdelmar

回答

1

如果您使用的是UIView子類,則可以實現以下方法以確定是否發生了敲擊。從那裏開始播放你的聲音。 (注意,使用ARC)

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    // now that we know that a touch has occurred, lets play a sound 
    NSString *pathToMySound = [[NSBundle mainBundle] pathForResource:@"mySound" ofType:@"aif"]; 
    SystemSoundID soundID; 
    AudioServicesCreateSystemSoundID([NSURL fileURLWithPath: pathToMySound], &soundID); 
    AudioServicesPlaySystemSound(soundID); 
} 
+0

所以基本上如果我複製那個「mySound」的例外,因爲我將它替換爲聲名,因爲我保存了它,就是這樣嗎?只需複製該代碼? – user3496401

+0

@ user3496401爲true。 –

+0

我輸入了這個和一個紅色!起來說它不能識別「soundPath」。我該怎麼辦? – user3496401

0

嘗試將UITapGestureRecogniser添加到可能爲self.view的主視圖或您命名的任何內容。

確保已啓用用戶交互,並創建一個選擇器,每次調用時都會播放聲音。

this article可能會幫助你,我沒有嘗試過,但它看起來像是朝着正確的方向前進。 雖然我會以編程方式添加UIGesture。

- 這是你如何箱子一個UITapGesture

//this stuff goes in your viewDidLoad for example 
UITapGestureRecognizer* singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doSthCool:)]; 
singleTap.numberOfTapsRequired = 1; 
singleTap.numberOfTouchesRequired = 1; 
[self addGestureRecognizer: singleTap]; //self or wherever you want to add it 

..... 
..... 

- (void) doSthCool: (UITapGestureRecognizer *)recognizer{ 
    //Code to handle the gesture 
    NSLog(@"flap"); 
} 

此外,試圖用一個URL時,不要我們CFURLRef,如果你不知道它在做,而不是嘗試是這樣的:

NSURL *path = [NSURL URLWithString:@"whatever the url/path is."]; 

我建議你谷歌的一些東西,當你遇到問題,這是一個學習:)

好運隊友的最好辦法! 並且有趣的編碼:)