每次打开应用程序时,我都会尝试播放一个循环声音文件。我这样做是因为我目前在我的初始viewController的viewDidLoad中有代码。问题是每次我切换视图然后回到初始视图控制器时,它会再次播放声音文件,声音会重叠,听起来很糟糕。我在下面发布了我的代码。非常感谢任何帮助,提前感谢!
{
if (![[NSUserDefaults standardUserDefaults]
boolForKey:@"loadSongOnce"]) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"Cartoon Sound" ofType:@"mp3"];
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
theAudio.numberOfLoops = -1;
[theAudio play];
[[NSUserDefaults standardUserDefaults] setBool:YES
forKey:@"loadSongOnce"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
答案 0 :(得分:1)
您需要做的是确定天气这是第一次加载应用程序。我们需要将这些数据存储为NSUserDefaults,因为它简单易用。
-(BOOL)application:(UIApplication *)application … {
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
if (! [defaults boolForKey:@"notFirstRun"]) {
// display alert...
[defaults setBool:YES forKey:@"notFirstRun"];
}
// rest of initialization ...}
基本上这告诉应用程序这是第一次加载应用程序,(播放声音,你添加它),如果没有(不播放声音)。声音播放后,bool将知道它应该更改为YES并且它将不再运行,直到您重新加载应用程序。当你回到视图时,这就是if语句发挥作用,告诉应用程序你已经播放了声音,并且不再播放它! 让我知道这是否有效,如果没有,我会看到我能做什么!
答案 1 :(得分:1)
试试这个
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
//self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
// self.window.rootViewController = self.viewController;
// [self.window makeKeyAndVisible];
if(![[[NSUserDefaults standardUserDefaults] valueForKey:@"firstTime"] isEqualToString:@"Yes"])
{
[[NSUserDefaults standardUserDefaults] setValue:@"Yes" forKey:@"firstTime"];
[[NSUserDefaults standardUserDefaults] setInteger:([[NSUserDefaults standardUserDefaults] integerForKey:@"ApplaunchCount"] + 1) forKey:@"ApplaunchCount"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
else
{
[[NSUserDefaults standardUserDefaults] setInteger:([[NSUserDefaults standardUserDefaults] integerForKey:@"ApplaunchCount"] + 1) forKey:@"ApplaunchCount"];
[[NSUserDefaults standardUserDefaults] synchronize];
if([[NSUserDefaults standardUserDefaults] integerForKey:@"ApplaunchCount"] % 1 ==0)
{
//Play sound file here
}
}
return YES;}
这表明每次应用程序被杀死(关闭是多任务处理)时,它都会重新启动声音。让我知道这是否有效,如果不让我知道,就像以前一样!