我试图用AVQueuePlayer以创建无缝音频循环,但是,我不知道为什么会出现环之间的细无声暂停?

2019-09-29 04:03发布

我有以.wav格式的简单的音频文件(音频文件是完全切断回路)。 我尝试了不同的方法来循环播放。 我第一次尝试是简单地使用AVPlayer和NSNotification检测时audioItem结束零寻求一次又一次播放。 然而,显然存在着一定的差距。

我一直在寻找不同的解决方案在网上,发现人们使用AVQueuePlayer做一个切换: 无缝循环AVPlayer

然而,实施时,这仍然会产生一定的差距。

这里是我当前的通知的代码:

weak var weakSelf = self
NSNotificationCenter.defaultCenter().addObserverForName(AVPlayerItemDidPlayToEndTimeNotification, object: nil, queue: nil, usingBlock: {(note: NSNotification) -> Void in

        if weakSelf?.currentQueuePlayer.currentItem == weakSelf?.currentAudioItemOne {

            weakSelf?.currentQueuePlayer.insertItem((weakSelf?.currentAudioItemTwo)!, afterItem: nil)
            weakSelf?.currentAudioItemTwo.seekToTime(kCMTimeZero)
        } else {
            weakSelf?.currentQueuePlayer.insertItem((weakSelf?.currentAudioItemOne)!, afterItem: nil)
            weakSelf?.currentAudioItemOne.seekToTime(kCMTimeZero)
        }

    })

这里是我的代码来设置当前QueuePlayer。

let audioPlayerItem = AVPlayerItem(URL: url)
currentAudioItemOne = audioPlayerItem


currentAudioItemTwo = audioPlayerItem

currentQueuePlayer = AVQueuePlayer()
currentQueuePlayer.insertItem(currentAudioItemOne, afterItem: nil)

currentQueuePlayer.play()

我在这个问题已经工作了好几天了。 任何线索或新的东西,试图将不胜感激。 我至今没有尝试过的唯一的事情是低质量的音频文件。 这些.wav文件都超过1MB,并且有被怀疑的文件大小可以影响到无缝循环。

编辑:

使用AVPlayerLooper创建“跑步机”的效果:

        let url = URL(fileURLWithPath: path)
        let audioPlayerItem = AVPlayerItem(url: url)
        currentAudioItemOne = audioPlayerItem

        currentQueuePlayer = AVQueuePlayer()
        currentAudioPlayerLayer = AVPlayerLayer(player: currentQueuePlayer)
        currentAudioLooper = AVPlayerLooper(player: currentQueuePlayer, templateItem: currentAudioItemOne)

        currentQueuePlayer.play() 

编辑2:

afinfo对我的wav文件之一:

Num Tracks:     1
----
Data format:     2 ch,  44100 Hz, 'lpcm' (0x0000000C) 16-bit little-endian signed integer
                no channel layout.
estimated duration: 11.302336 sec
audio bytes: 1993732
audio packets: 498433
bit rate: 1411200 bits per second
packet size upper bound: 4
maximum packet size: 4
audio data file offset: 44
not optimized
source bit depth: I16
----

Answer 1:

您要插入的项目在当前的解决方案为时已晚。 您需要排队超过一个初始项目,所以总是有一个底漆AVPlayerItem蓄势待发。

这就是所谓的AVPlayerQueue “跑步机模式”作为在这个WWDC 2016会议上更好地描述 。 如果你的目标iOS的10,可以使用新的AVPlayerLooper类会为你(在相同的链接也被描述)。 苹果还提供了一个样本项目提供两种策略的一个例子。

较低级别的解决方案包括排队的音频缓冲到AVAudioEngine实例或使用AudioQueue或自己用捣碎的缓冲区一起AudioUnit



文章来源: I'm trying to use AVQueuePlayer to create a seamless audio loop, however, I don't know why there is a small silent pause between loops?