playAtTime不起作用,但play()与Swift中的AVAudioPlayer()一起使用

时间:2016-05-07 20:25:23

标签: ios swift

每当我使用musicPlayer.play()运行我的应用程序时没有问题,但我希望应用程序从特定点开始,当我使用playAtTime(timeToPlay)时,音频永远不会播放。我附上了我的代码的顶部(我相信这是唯一相关的部分)。任何帮助都会很棒!

导入UIKit 导入AVFoundation 进口基金会

类RHCPViewController:UIViewController {

var backgroundMusicPlayer = AVAudioPlayer()
let gradientLayer = CAGradientLayer()
var isPlaying: Bool = false
var timer: NSTimer?
var timeToPlay: NSTimeInterval = 0.00

override func viewDidLoad() {
    super.viewDidLoad()

    UIApplication.sharedApplication().statusBarHidden =  true

}


@IBAction func playButtonWasClicked(sender: AnyObject) {

    if isPlaying == false {
        let song = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("CantStop", ofType: "mp3")!)

        do {
            backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: song, fileTypeHint: nil)
            backgroundMusicPlayer.numberOfLoops = -1
            backgroundMusicPlayer.prepareToPlay()
            backgroundMusicPlayer.playAtTime(timeToPlay)
            isPlaying = true
        }

        catch let error as NSError {
            print(error.description)
        }

1 个答案:

答案 0 :(得分:0)

您已将0.0传递给playAtTime,但时间参数必须大于音频设备的当前时间。在计算时间参数时使用deviceCurrentTime属性,如下所示:

backgroundMusicPlayer.playAtTime(backgroundMusicPlayer.deviceCurrentTime + timeToPlay)

另请参阅API docs