我正在尝试运行 3 个音频文件一段特定的时间然后停止它们。我可以同时播放所有 3 个音频文件,不用担心,但是当我尝试停止它们时,我收到此错误:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController stopMusic:]: unrecognized selector sent to instance
这是我的代码播放文件的样子:
- (void)backgroundTap {
[customerNameTextField resignFirstResponder];
[customerEmailTextField resignFirstResponder];
if ((audioPlayer) || (audioPlayer2) || (audioPlayer3)) {
NSLog(@"still playing");
} else {
[NSTimer scheduledTimerWithTimeInterval:10.0
target:self
selector:@selector(stopMusic:)
userInfo:nil
repeats:NO];
// create audio session
[[AVAudioSession sharedInstance] setDelegate: self];
NSError *setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryError];
if (setCategoryError)
NSLog(@"Error setting category! %@", setCategoryError);
// path
NSString *soundPath =[[NSBundle mainBundle] pathForResource:@"tuiSong" ofType:@"mp3"];
NSURL *soundURL = [NSURL URLWithString:soundPath];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];
audioPlayer.numberOfLoops = 0;
[audioPlayer setVolume: 0.1];
// path
NSString *soundPath2 =[[NSBundle mainBundle] pathForResource:@"beachSong" ofType:@"mp3"];
NSURL *soundURL2 = [NSURL URLWithString:soundPath2];
NSError *error2;
audioPlayer2 = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL2 error:&error2];
audioPlayer2.numberOfLoops = 0;
[audioPlayer2 setVolume: 0.06];
// path
NSString *soundPath3 =[[NSBundle mainBundle] pathForResource:@"CicadaSong" ofType:@"mp3"];
NSURL *soundURL3 = [NSURL URLWithString:soundPath3];
NSError *error3;
audioPlayer3 = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL3 error:&error3];
audioPlayer3.numberOfLoops = 5;
[audioPlayer3 setVolume: 0.05];
// play bells
if (!audioPlayer) {
NSLog(@"localizedDescription : %@", [error localizedDescription]);
} else {
if (![audioPlayer isPlaying]) {
[audioPlayer play];
}
if (![audioPlayer2 isPlaying]) {
[audioPlayer2 play];
}
if (![audioPlayer isPlaying]) {
[audioPlayer3 play];
}
}
}
}
然后这就是我停止音频的方法。
- (void)stopMusic {
if ([audioPlayer isPlaying]) {
[audioPlayer stop];
audioPlayer = nil;
}
if ([audioPlayer2 isPlaying]) {
[audioPlayer2 stop];
audioPlayer2 = nil;
}
if ([audioPlayer3 isPlaying]) {
[audioPlayer3 stop];
audioPlayer3 = nil;
}
}
最佳答案
错误消息完美地描述了问题。您的 NSTimer 正在调用 stopMusic:
。但是没有方法 stopMusic:
。有一个方法 stopMusic
。 stopMusic
与 stopMusic:
不同(带冒号)。您必须完全正确地取名。
关于ios - 调用停止时 AVAudioPlayer 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20694587/