您可以使用NSUserDefaults的保存音樂播放狀態,這樣的觀點在加載時,音樂將只如果有尚未發揮。
if ([[NSUserDefaults standardUserDefaults] stringForKey:@"music"] == nil) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"drums" ofType:@"mp3"];
theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPathath] error:NULL];
theAudio.delegate = self;
theAudio.numberOfLoops = -1;
[theAudio play];
[[NSUserDefaults standardUserDefaults] setObject:@"-" forKey:@"music"]; }
當退出應用程序時,您需要將此鍵重置爲零。否則,如果玩家退出應用程序,並且下次重新啓動應用程序時,@「music」字符串不會爲零。
轉到projectAppDelegate.m文件:
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"music"]; }
如果音樂被整個應用播放,然後把音樂,如下圖所示是安全的打碼。不要忘記在projectAppDelegate.h文件中聲明AVAudioPlayer * theAudio。
- (void)applicationDidBecomeActive:(UIApplication *)application {
NSString *path = [[NSBundle mainBundle] pathForResource:@"drums" ofType:@"mp3"];
theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPathath] error:NULL];
theAudio.delegate = self;
theAudio.numberOfLoops = -1;
[theAudio play];
[[NSUserDefaults standardUserDefaults] setObject:@"-" forKey:@"music"]; }
我可能在這裏錯過了幾位。只需運行一些測試,使其成爲您喜歡的工作方式。我只是嘗試了我的應用程序,它爲我工作。
'theAudio'是什麼? – 2012-07-10 11:29:47