0

I'm playing an audio file in the background when the app is started. The function is called in viewDidLoad.

-(void)playsong
{
    NSString *songUrl = [[NSBundle mainBundle] pathForResource:@"chant" ofType:@"m4a"];
    NSData *songFile = [NSData dataWithContentsOfFile:songUrl];

    NSError *error; 
    audioPlayer = [[AVAudioPlayer alloc] initWithData:songFile error:&error ];
    [audioPlayer play];
}

When the user presses the home button, and the song's current position is 10 secs, the song will stop playing. But when the user opens the app again, the song starts from the same position.

I'd like it to be started from the beginning every time the app is opened.

Plus for memory reasons wouldn't it be better to deallocate the memory?

I tried to call the function from

- (void)viewWillAppear:(BOOL)animated

and then set it to nil in

- (void)viewWillDisappear:(BOOL)animated

but the method - (void)viewWillDisappear:(BOOL)animated isn't getting called.

4

1 回答 1

1

如果 viewWillDisappear 对您不起作用,请尝试在 NSNotification 中心添加一个观察者,该观察者在应用程序 didEnterBackground 时调用一个方法。像这样:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(enteredBackground:)
                                             name:UIApplicationDidEnterBackgroundNotification
                                           object:nil];

然后将您的代码添加到此方法中:

-(void)enteredBackground:(NSNotification *)notification {

}

希望这可以帮助!

更新

好的,所以从你想在 about us 视图中访问音频对象的位置,试试这个:

HomeViewController *HomeVC = [HomeViewController alloc] init]; 

HomeVC.audioPlayer...//then do what you want with it

只要您在家庭 VC 中声明了音频对象,那么这应该可以工作。

确保您已将 homeview 控制器导入到 about us 视图控制器和文件之一中。

于 2013-06-30T14:25:27.120 回答