2011-09-18 1 views
1

特定のボタンが(iOS)に保持されている間だけサウンドファイルを再生してループさせるにはどうすればよいですか?ボタンが離れるときに停止する必要もありますか?私はGoogleを検索しようとしているだけで、それを行う方法については本当の答えは尋ねる人々とフォーラムを見つけた。ボタンがXcodeに保持されている限りサウンドループを作成するには?

答えて

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

編集: は、あなたの質問には、サウンドファイルを再生する詳細されている可能性があり実現しました!メインファイル内のボタンのためのあなたのibactionsを作成

輸入枠組みとプレイヤーに

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

を定義します:

異なるフレームワークがあります、あなたはAVAudioPlayerを使用することができ

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

あなたのコードはコードでなければなりません。しかし、ボタンはIBで行うことができます。コネクションインスペクタで対応するcontroleventsがある場合は、これらをヘッダーファイルで宣言したuiviewcontrollerで実装したibactionsに接続します。これはおそらく "ファイルの所有者"になります –

+0

これは完璧に機能しました!どうもありがとうございます!私はstartMusicを「タッチダウン」に接続し、stopMusicを「タッチアップ」に接続しました。再度、感謝します! –

関連する問題