我試圖在我的應用程序中播放音樂。音樂工作正常,但切換viewControllers並返回到主菜單後,我的音樂再次播放!這意味着幾個相同的聲音一起玩!我該如何解決這個問題?這裏是我的代碼:iOS SDK:在背景上播放音樂並切換視圖
- (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];
}
}
我有,嘗試從您的appdelegate文件播放音樂,即使你切換視圖 – Leena