这是我的代码
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"95" ofType:@"wav"];
NSError *activationError = nil;
NSError *audioPlayerInitError = nil;
[[AVAudioSession sharedInstance] setActive: YES error:&activationError];
NSURL *newURL = [NSURL fileURLWithPath:soundFilePath];
musicPlayer1 = [[AVAudioPlayer alloc] initWithContentsOfURL:newURL error:&audioPlayerInitError];
if (musicPlayer1) {
[musicPlayer1 stop];
[musicPlayer1 release];
musicPlayer1 = nil;
}
else {
[musicPlayer1 prepareToPlay];
[musicPlayer1 setVolume:.8];
[musicPlayer1 setNumberOfLoops:-1]; // -1 means play indefintely
[musicPlayer1 setDelegate: self];
[musicPlayer1 play];
}
}
我想用相同的按钮启动和停止AVAudioPlay(musicPlayer1在标题中)。现在,当我触摸按钮时,它不会播放任何内容。请帮忙?
最佳答案
您每次都在创建一个新的AVAudioPlayer
实例。您需要保留对某个对象的引用,然后再返回该引用。在您的 View Controller 类中添加一个字段:
@private AVAudioPlayer *currentAudio;
然后在此方法中进行以下更改:
if (currentAudio) {
[currentAudio stop];
[currentAudio release];
currentAudio = nil;
} else {
// what you already have goes here
}
关于iphone - 停止AVAudioPlayer,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5514772/