【问题标题】:iOS: Reset audioplayer when the app is no longer in the foregroundiOS:当应用程序不再在前台时重置音频播放器
【发布时间】:2013-06-30 13:03:49
【问题描述】:

应用启动时,我正在后台播放音频文件。该函数在 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];
}

当用户按下主页按钮,歌曲的当前位置为 10 秒时,歌曲将停止播放。 但当用户再次打开应用时,歌曲从同一位置开始播放。

我希望每次打开应用时都从头开始。

加上内存的原因,释放内存不是更好吗?

我尝试从

调用该函数
- (void)viewWillAppear:(BOOL)animated

然后在

中设置为nil
- (void)viewWillDisappear:(BOOL)animated

但是方法 - (void)viewWillDisappear:(BOOL)animated 没有被调用。

【问题讨论】:

    标签: ios avaudioplayer viewwillappear


    【解决方案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 视图控制器之一中。

    【讨论】:

    • 谢谢它的工作!只有一件事,如果我导航到“关于我们”视图然后关闭应用程序。在重新打开歌曲从相同的位置重新开始。如何访问“关于我们”视图的“主页”视图中定义的音频对象?
    猜你喜欢
    • 2021-01-05
    • 2014-06-11
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    相关资源
    最近更新 更多