我正在尝试在我的应用程序中播放音乐。音乐播放正常,但在切换 viewControllers 并返回主菜单后,我的音乐再次播放!这意味着几个相同的声音一起播放!我该如何解决这个问题?这是我的代码:
- (void)viewDidLoad {
NSString *music = [[NSBundle mainBundle] pathForResource:@"1music" ofType:@"mp3"];
myMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:music] error:NULL];
myMusic.delegate = self;
myMusic.numberOfLoops = -1;
[myMusic play];
}
- (IBAction) scoreView {
ScoreViewController *scoreView = [[ScoreViewController alloc] initWithNibName:@"ScoreViewController" bundle:nil];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.view cache:YES];
[self.view addSubview: scoreView.view];
[UIView commitAnimations];
}
编辑代码:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
NSString * musicSonati = [[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"];
myMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:musicSonati] error:NULL];
myMusic.delegate = self;
myMusic.numberOfLoops = -1;
[myMusic play];
}
return self;
}
//toggle button
- (IBAction)MusicPlaying:(id)sender {
if ((isPlay = !isPlay))
{
UIImage *buttonImageNormal = [UIImage imageNamed:@"play.png"];
UIImage *stretchableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:0 topCapHeight:0];
[MusicButton setBackgroundImage:stretchableButtonImageNormal forState:UIControlStateNormal];
[myMusic pause];
}else {
UIImage *buttonImageNormal = [UIImage imageNamed:@"pause.png"];
UIImage *stretchableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:0 topCapHeight:0];
[MusicButton setBackgroundImage:stretchableButtonImageNormal forState:UIControlStateNormal];
NSLog(@"Music play");
[myMusic play];
}
}
最佳答案
如果您要在多个地方播放音频,那么实现此目的的一种简单方法是在具有合成属性的委托(delegate)中声明 AVAudioPlayer 实例。如果您想在任何地方播放它,请执行以下操作:-
MyAppDelegate *app_delegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
if(app_delegate.audioPlayer)
{
[app_delegate.audioPlayer release];
app_delegate.audioPlayer = nil;
}
app_delegate.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
如果你想停止声音,这样做:-
if(app_delegate.audioPlayer)
{
if([app_delegate.audioPlayer isPlaying])
{
[app_delegate.audioPlayer stop];
[app_delegate.audioPlayer setCurrentTime:0];
}
}
如果已经分配或使用新的声音文件 url 再次分配它,则播放新的声音文件发布和零相同的播放器。
关于iphone - iOS SDK : playing music on the background and switching views,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8467533/