2011-07-20 1 views
1

私はn00bであり、助けを求めています。私は音を停止し、再生したい同じボタンでサウンドをオン/オフに切り替えるカスタムUIButtonを作成する方法

- (void)addButtonSpeaker { 
UIButton *buttonSpeaker = [UIButton buttonWithType:UIButtonTypeCustom]; 
          [buttonSpeaker setFrame:CGRectMake(650, 930, 63, 66)]; 
[buttonSpeaker setBackgroundImage:[UIImage imageNamed:@"buttonLesen.png"] 
         forState:UIControlStateNormal]; 
[buttonSpeaker addTarget:self action:@selector(playAudio) 
     forControlEvents:UIControlEventTouchUpInside]; 
[self.view addSubview:buttonSpeaker]; 
} 

- (void)playAudio { 
NSString *path = [[NSBundle mainBundle] pathForResource:@"Vorwort" ofType:@"mp3"]; 
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL  
fileURLWithPath:path] error:NULL]; 
self.audioPlayer = theAudio; 
[theAudio release]; 
[theAudio play]; 
} 

今、私は、次のコードでサウンドファイルを起動することができます。 たぶん私は間違ったことを探していますが、ウェブ上で適切な情報を見つけることができません。

誰かがチュートリアルなどのリンクを私に与えることができたら本当に役に立ちます。事前に

おかげで Planky

+0

あなたはtoggleAudio' 'で' playAudio'メソッドの名前を変更し、あなたが私の一日行わ –

答えて

1

loadViewメソッドどこかにAVAudioPlayerプレイヤオブジェクトを作成します。

- (void)loadView { 

    // Some code here 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Vorwort" ofType:@"mp3"]; 
    AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 
    self.audioPlayer = theAudio; 
    [theAudio release]; 
    // Some code here 
} 

は次にボタンのアクション内で(他の人が提案したよう toggleAudioにアクション名を変更する)には、オーディオが再生されているかどうかを確認するためにをisPlayingプロパティ を取得し、それぞれのアクションを行うことができます。

- (void)toggleAudio { // original name is playAudio 

    if ([self.audioPlayer isPlaying]) { 

     [self.audioPlayer pause]; 
     // Or, [self.audioPlayer stop]; 

    } else { 

     [self.audioPlayer play]; 
    } 
} 
+0

そこに音を再生するトグル扱うことができます!オーストリアから感謝します。 – Planky

+0

ようこそ。インドからの応援! ;-) – EmptyStack

関連する問題