Как сделать пользовательскую кнопку UIB для включения / выключения звука - PullRequest
1 голос
/ 20 июля 2011

Я n00b и ищу помощи.

Теперь я могу запустить звуковой файл с помощью следующего кода:

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

1 Ответ

1 голос
/ 20 июля 2011

Создайте объект игрока AVAudioPlayer на loadView или где-либо еще.

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