#iphone #objective-c #cocoa-touch #xcode
#iPhone #objective-c #cocoa-touch #xcode
Вопрос:
У меня зациклен звук, это прямая кнопка, как только пользователь нажимает на кнопку, звук зацикливается и воспроизводится. Я хочу, чтобы после повторного нажатия пользователем той же кнопки воспроизведение звука прекращалось.
Это код
- (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:amp;error];
if (error)
NSLog(@"%@",[error localizedDescription]);
threeAudio.numberOfLoops = -1;
threeAudio.delegate = self;
[threeAudio play];
}
Спасибо
Ответ №1:
Довольно прямолинейно…
- (IBAction)threeSound:(id)sender; {
if (threeAudio amp;amp; 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:amp;error];
if (error)
NSLog(@"%@",[error localizedDescription]);
threeAudio.numberOfLoops = -1;
threeAudio.delegate = self;
[threeAudio play];
}
Комментарии:
1. Этот код также предполагает, что threeSound вызывается для обоих событий.
2. Он упомянул «снова нажал ту же кнопку», поэтому я думаю, что это правильно.
3. Извините, я согласен с вами, просто уточняю на случай, если появится кто-то еще. =)
Ответ №2:
Вы должны разделить эти два процесса на этот
`- (void)initSound {
NSString *path = [[NSBundle mainBundle] pathForResource:@"3" ofType:@"wav"];
NSError *error = nil;
threeAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:amp;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
Это мой совет 😉
Комментарии:
1. Это усложняет код, если только вы не останавливаете / запускаете звук из других мест, а не только с помощью кнопки, и в этом случае это упростило бы код. Но в любом случае работает.