菜鸟教程小白 发表于 2022-12-11 18:33:45

ios - AVPlayer 在后台 View Controller 中缓冲视频会导致内存问题


                                            <p><p>我正在制作一个带有 AVPlayer 的 ViewController 的直播电视流媒体应用。</p>

<pre><code>- (void)viewDidLoad {
    self.playerViewController = [ init];
    self.playerViewController.player = ];
    ;
    ;
    ;
}
</code></pre>

<p>我还有一个按钮,它显示一个带有附加信息的新 ViewController 。当我展示新的 ViewController 时, <code>AVPlayer</code> 会继续播放音频,这就是我想要的。 </p>

<p>问题是 - 当我展示新的 ViewController 时,<code>AVPlayer</code> 在后台播放音频但继续缓冲视频,当 ViewController 被关闭时,<code>AVPlayer</code> 快进视频,以便它可以与音频同步。快速转发导致内存使用量大幅增加,并且我收到内存不足警告。新 ViewController 在前台的时间越长,当我关闭它时,内存跳跃就越大。</p>

<p>如何阻止 <code>AVPlayer</code> 缓冲视频? </p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>我可能会迟到一点,但如果有人对此仍有疑问,我可以建议减少进入后台时的播放器缓冲区。我知道这不是一个完美的答案,但这仍然会有所帮助。</p>

<pre><code>[ addObserver:self
                                       selector:@selector(onApplicationDidEnterBackgroundNotification:)
                                             name:UIApplicationDidEnterBackgroundNotification
                                           object:nil];

[ addObserver:self
                                       selector:@selector(onApplicationWillEnterForegroundNotification:)
                                             name:UIApplicationWillEnterForegroundNotification
                                           object:nil];
</code></pre>

<p>然后</p>

<pre><code>- (void)onApplicationDidEnterBackgroundNotification:(NSNotification *)notification {
    self.playerItem.preferredForwardBufferDuration = 1;
}
- (void)onApplicationWillEnterForegroundNotification:(NSNotification *)notification {
    self.playerItem.preferredForwardBufferDuration = 0;
}
</code></pre>

<p>别忘了在 dealloc 中移除观察者</p>

<pre><code> [ removeObserver:self];
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - AVPlayer 在后台 ViewController 中缓冲视频会导致内存问题,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/41599605/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/41599605/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - AVPlayer 在后台 View Controller 中缓冲视频会导致内存问题