Frage

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.

War es hilfreich?

Lösung

If viewWillDisappear isn't working for you, try adding an observer in NSNotification center, which calls a method when the application didEnterBackground. Like so:

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

Then add your code into this method:

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

}

Hope this helps!

UPDATE

Okay, so from where you want to acces the audio object in the about us view, try this:

HomeViewController *HomeVC = [HomeViewController alloc] init]; 

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

As long as you have declared the audio object in the home VC then this should work.

Make sure you have imported the homeview controller in one of the about us view controller, files as well.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top