2016-05-07 39 views
-1

每當我只用musicPlayer.play()運行我的應用程序時,就沒有問題,但我希望應用程序從特定點開始,當我使用playAtTime(timeToPlay)音頻從不播放。我附上我的代碼的頂部(我相信它是唯一相關的部分)。任何幫助都是極好的!playAtTime不起作用,但play()與Swift中的AVAudioPlayer()

進口的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) 
     } 
+0

有助於閱讀文檔:https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVAudioPlayerClassReference/#//apple_ref/occ/instm/AVAudioPlayer/playAtTime:他們甚至給你一個例子。 – matt

回答

0

你傳遞0.0playAtTime,但時間參數必須比音頻設備的當前時間大。使用deviceCurrentTime屬性在計算時間參數如下:

backgroundMusicPlayer.playAtTime(backgroundMusicPlayer.deviceCurrentTime + timeToPlay) 

又見API docs

相關問題