Как остановить звук - Какао Touch - PullRequest
0 голосов
/ 27 апреля 2011

У меня есть зацикленный звук, это прямоугольная кнопка, когда пользователь нажимает кнопку, звук зацикливается и воспроизводится. Я хочу, чтобы, как только пользователь снова нажал ту же кнопку, звук прекратился.

Это код

- (IBAction)threeSound:(id)sender; {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"3" ofType:@"wav"];
    if (threeAudio) [threeAudio release];
    NSError *error = nil;
    threeAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
    if (error)
        NSLog(@"%@",[error localizedDescription]);
    threeAudio.numberOfLoops = -1;
    threeAudio.delegate = self;
    [threeAudio play];  

}

Спасибо

Ответы [ 2 ]

1 голос
/ 27 апреля 2011

Довольно прямолинейно ...

- (IBAction)threeSound:(id)sender; {
    if (threeAudio && threeAudio.playing) {
         [threeAudio stop];
         [threeAudio release];
         threeAudio = nil;
         return;
    }         
    NSString *path = [[NSBundle mainBundle] pathForResource:@"3" ofType:@"wav"];
    if (threeAudio) [threeAudio release];
    NSError *error = nil;
    threeAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
    if (error)
        NSLog(@"%@",[error localizedDescription]);
    threeAudio.numberOfLoops = -1;
    threeAudio.delegate = self;
    [threeAudio play];  

}
0 голосов
/ 27 апреля 2011

Вы должны разделить эти два процесса на этот

`- (void)initSound {
 NSString *path = [[NSBundle mainBundle] pathForResource:@"3" ofType:@"wav"];
NSError *error = nil;
    threeAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
    if (error)
        NSLog(@"%@",[error localizedDescription]);
    threeAudio.numberOfLoops = -1;
    threeAudio.delegate = self;
    [threeAudio prepareToPlay];
    [threeAudio play];
}

-(IBAction)threeSound:(id)sender:(UIButton *)sender{
    if (sender.selected) {
    [threeAudio pause];
    } else {
    threeAudio.currentTime = 0;     
        [threeAudio play];
    }
    sender.selected = !sender.selected;
}`

Обратите внимание, что initSound должен вызываться в какой-то момент, если вы хотите запустить звук только кнопкой ... затем добавьте

if (!threeAudio) {
       [self initSound];
}

в начале IBAction

Вот мой совет;)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...