2011-09-18 40 views

回答

2

用按鈕控制的事件着陸,touchupinside和touchupoutside:

UIButton *theButton = [[UIButton alloc]initWithFrame:CGRectMake(40.0, 40.0, 200.0, 30.0)]; 
[theButton setTitle:@"button" forState:UIControlStateNormal]; 
[theButton setBackgroundColor:[UIColor redColor]]; 
[theButton addTarget:self action:@selector(startMusic) forControlEvents:UIControlEventTouchDown]; 
[theButton addTarget:self action:@selector(stopMusic) forControlEvents:UIControlEventTouchUpInside]; 
[theButton addTarget:self action:@selector(stopMusic) forControlEvents:UIControlEventTouchUpOutside]; 

編輯: 意識到你的問題可能已經更多關於播放聲音文件?

有不同的框架,你可以使用AVAudioPlayer:

進口框架,並定義一個球員

#import <AVFoundation/AVFoundation.h> 
AVAudioPlayer *newPlayer; 

在主文件中創建您的按鈕ibactions:

-(IBAction)startMusic{ 
    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: @"mySoundFile" 
                  ofType: @"wav"]; 
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath]; 
    newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: nil]; 
    newPlayer.numberOfLoops = -1; // Loop indefinately 
    [newPlayer play]; 
} 

-(IBAction)stopMusic{ 
    if(newPlayer isPlaying){ 
     [newPlayer stop]; 
    } 
    [newPlayer release]; 
} 
+0

如何在Interface Builder中連接所有這些? –

+0

您的ibactions必須是代碼。但是,按鈕可以在IB中完成。在你有相應的controlevents的連接檢查,這些連接到你的UIViewController中(在頭文件中聲明他們)實施ibactions,這將極有可能是「文件的所有者」 –

+0

它完美!非常感謝!我只是將startMusic連接到「觸摸」並停止音樂以「觸及內部」。再次感謝! –