我目前在我的应用程序中播放背景音乐。 在:检查音乐是否正在播放
-(void)viewDidLoad
我开始了音乐,使用:
[self LoadMusic];
这基本上启动然后音乐缓冲区,如果设置指出“声音是在”音乐开始。
我遇到的问题是当我移动视图时,音乐继续播放(因为它应该),但是当你回到音乐最初开始的视图控制器时,它会再次激活。
所以你最终会得到相同的音乐循环。
我已经尝试了一些东西,比如:
if(MusicPlay.playing){
// do nothing
}else{
// start music
[self LoadMusic];
}
这是loadMusic
- (void) LoadMusic{
//Notification for stoping
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopMusic) name:@"StopMusic" object:nil];
//Notification for playing
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playMusic) name:@"PlayMusic" object:nil];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *SoundSwitch = [defaults stringForKey:@"Sound_EnabledS"];
// grab the path to the caf file
NSString *soundFilePath =
[[NSBundle mainBundle] pathForResource: @"Menu_Loop"
ofType: @"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
// create a new AVAudioPlayer initialized with the URL to the file
AVAudioPlayer *newPlayer =
[[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
error: nil];
// set our ivar equal to the new player
self.MusicPlay = newPlayer;
// preloads buffers, gets ready to play
[MusicPlay prepareToPlay];
MusicPlay.numberOfLoops = -1; // Loop indefinately
if ([SoundSwitch isEqualToString:@"1"]){
[self.MusicPlay play]; // Plays the sound
}else{
[self.MusicPlay stop]; // Stops the sound
}
}
的代码,但因为它没有看到MusicPlay.playing是唯一真正的一次,这是行不通该视图已'重新启动'
如果有人有一个很好的方法来解决这个问题。 请让我知道。
谢谢。
你能PLZ粘贴LoadMusic方法的代码 –
见上面检查。谢谢。 –