如何播放音频文件示例

How to play an audio file sample

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

音乐文件大约2-3分钟长。我的开始时间是 42sec 秒。然而,这首歌唱到最后。我正在尝试将音频文件设为 30 秒的样本。所以它应该从 42 秒开始,到 1 分 12 秒结束。

非常感谢任何帮助。

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

我还能想到另一种极端情况 — 如果您 hide/close 视图控制器,您可能还想停止该计时器。

override func viewWillDisappear(_ animated: Bool) {
    timer?.invalidate()
}