【问题标题】:How to play an audio file sample如何播放音频文件示例
【发布时间】:2017-03-29 18:56:01
【问题描述】:

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

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

感谢任何帮助。

【问题讨论】:

  • 我建议使用Timer。如果用户过早停止播放,您必须使其无效。
  • 嘿,nshuman,AVFoundation 对我来说是新的。因此,如果您不介意向我提供一些示例代码,我将不胜感激。与此同时,我将继续阅读有关 AVFondation 的更多信息。
  • 嘿@luis-ramirez,我已经发布了带有示例代码的答案,请查看。

标签: ios swift3 avaudioplayer


【解决方案1】:

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

【讨论】:

  • 谢谢nshuman,它运行良好。我需要阅读更多关于 AVFoundation 原因不要和 Timer 的信息。因为我不完全知道发生了什么。再次感谢你。 :)
猜你喜欢
  • 1970-01-01
  • 2020-09-17
  • 1970-01-01
  • 2018-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多