好的,我试着做一些类似iTunes的事情,不确定它是否仍然是一样的。这是当你点击一首歌,它提供一个音频文件的样本。这是我的密码。

音乐文件大概有2-3分钟长。我有42秒的开始时间。然而,这首歌最终结束了。我试着把音频文件做成30秒的样本。所以它应该从42秒开始,到1分12秒结束。
如果能帮忙的话,谢谢。
发布于 2017-03-29 23:25:19
每次您的音频示例开始播放时,您都可以创建一个Timer对象,它将使您的播放器在给定的时间内停止播放。
var audioPlayer = AVAudioPlayer()
var timer: Timer?
func prepareMusic() {
....
// Your code to start playing sample
audioPlayer.currentTime = 42
audioPlayer.play()
// Here we are stopping previous timer if there was any, and creating new one for 30 seconds. It will make player stop.
timer?.invalidate()
timer = Timer(fire: Date.init(timeIntervalSinceNow: 30), interval: 0, repeats: false) { (timer) in
if self.audioPlayer.isPlaying {
self.audioPlayer.stop()
}
}
RunLoop.main.add(timer!, forMode: .defaultRunLoopMode)
}
func musicButton(sender: UIButton) {
....
// If sample is stopped by user — stop timer as well
if audioPlayer.isPlaying {
audioPlayer.stop()
timer?.invalidate()
}
}还有一个边缘的情况,我可以想到-如果你隐藏/近距离控制器,你也可能想停止那个定时器。
override func viewWillDisappear(_ animated: Bool) {
timer?.invalidate()
}https://stackoverflow.com/questions/43101907
复制相似问题