如何播放音频文件样本

时间:2017-03-29 18:56:02

标签: ios swift3 avaudioplayer

好吧我正在尝试做类似于iTunes的事情,不确定它是否仍然相同。当您单击一首歌曲时,它会提供音频文件的样本。这是我的代码看起来。

enter image description here

音乐文件长度为2-3分钟。我的开始时间是42秒开始。然而,这首歌结束了。我正在尝试将音频文件设为30秒的样本。因此它应该从42秒开始并在1分12秒结束。

感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

每次音频样本开始播放时,您都可以创建一个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()
}