gpt4 book ai didi

Swift:在歌曲的某些部分引发 Action (avaudioplayer)

转载 作者:行者123 更新时间:2023-11-30 13:34:43 25 4
gpt4 key购买 nike

我正在使用 AVAudioPlayer 播放歌曲,当歌曲达到 30 秒标记时,我想触发一个 Action (调用函数)。当歌曲完成时我知道该怎么做:

func play(url: NSURL) {
let item = AVPlayerItem(URL: url)

NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:", name: AVPlayerItemDidPlayToEndTimeNotification, object: item)

let player = AVPlayer(playerItem: item)
player.play()
}

func playerDidFinishPlaying(note: NSNotification) {
// Your code here
}

但是,我想做类似的事情,但是当歌曲达到 30 秒时。这可能吗?现在我必须使用 NSTimers 但它不可靠。

谢谢!

最佳答案

不确定这是否昂贵,但效果很好。

首先,我运行一个循环,多次调用“checkForStrobe”:

var dpLink : CADisplayLink?
dpLink = CADisplayLink(target: self, selector: "checkForStrobe")
dpLink?.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)

然后我只需将其放入我的 checkForStrobe 函数中即可:

func checkForStrobe(){
//This is being called repeatedly checking if its time to run strobe
if(backgroundAudio.currentTime >= 38.5 && backgroundAudio.currentTime <= 38.6){
runStrobe()
}
if(backgroundAudio.currentTime >= 63.5 && backgroundAudio.currentTime <= 63.6){
stopStrobe()
}
if(backgroundAudio.currentTime >= 125.0 && backgroundAudio.currentTime <= 125.1){
runStrobe()
}
if(backgroundAudio.currentTime >= 150.0 && backgroundAudio.currentTime <= 150.1){
stopStrobe()
}
}

这解决了我的问题。

关于Swift:在歌曲的某些部分引发 Action (avaudioplayer),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36212744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com