如何获得AvPlayer持续时间 - 斯威夫特

时间:2016-02-14 05:24:30

标签: ios swift avplayer avplayeritem

如何让 AvPlayer AvAudioPlayer 一样工作。我的意思是,我似乎无法持续工作。以下是我需要转换为 AvPlayer

的内容
import UIKit
import AVKit
import AVFoundation


class ModalViewController: UIViewController {

    var audioPlayer = AVAudioPlayer()
    let varSend = VarSend.sharedInstance
    var timer:NSTimer!
    var toggleState = 2


    @IBOutlet weak var slider: UISlider!
    @IBOutlet weak var sermonImage: UIImageView!
    @IBOutlet weak var sermont: UILabel!
    @IBOutlet weak var sermond: UILabel!
    @IBOutlet weak var sermonE: UILabel!
    @IBOutlet weak var sermonL: UILabel!
    @IBOutlet weak var play: UIButton!
    @IBOutlet var layer: UIView!


    override func viewDidLoad() {

        super.viewDidLoad()
        let url = varSend.url
        print("Setting up.")



        do {
           let data1 =  NSData(contentsOfURL: NSURL(string:url)!)
            audioPlayer = try AVAudioPlayer(data: data1!)
            audioPlayer.prepareToPlay()
            audioPlayer.volume = 1.0
            audioPlayer.play()
        } catch {
            print("Error getting the audio file")
        }



        slider.maximumValue = Float(audioPlayer.duration)
        timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("updateSlider"), userInfo: nil, repeats: true)
        slider.setThumbImage(UIImage(named: "circle"), forState: .Normal)
        slider.setThumbImage(UIImage(named: "circle"), forState: .Highlighted)


        let title = varSend.sermonName
        self.sermont.text = title

        let date = varSend.sermonDate
        self.sermond.text = date

        let image = varSend.sermonPic

        ImageLoader.sharedLoader.imageForUrl(image, completionHandler:{(image: UIImage?, url: String) in
            self.sermonImage.image = image!
        })
    }

    @IBAction func ChangeAudioTime(sender: AnyObject) {
        audioPlayer.stop()
        audioPlayer.currentTime = NSTimeInterval(slider.value)
        audioPlayer.prepareToPlay()
        audioPlayer.volume = 1.0
        audioPlayer.play()

    }



    func updateSlider() {
        slider.value = Float(audioPlayer.currentTime)
        let currentTime = Int(audioPlayer.currentTime)
        let minutes = currentTime / 60
        let seconds = currentTime - minutes * 60
        let con = Int(audioPlayer.duration)
        let currentItem = con - currentTime
        let minutesU = Int(currentItem / 60)
        let secondsU = Int(currentItem % 60)
        sermonE.text = NSString(format: "%02d:%02d", minutes,seconds) as String
        let timeLeft = NSString(format: "%02d:%02d", minutesU,secondsU) as String
        sermonL.text = "-\(timeLeft)"

        if currentItem == 1 {
            //audioPlayer.pause()
            toggleState = 1
            print(toggleState)
            play.setImage(UIImage(named:"play.png"),forState:UIControlState.Normal)
        }
    }


    @IBAction func playPauseButton(sender: AnyObject) {
        let playBtn = sender as! UIButton
        if toggleState == 1 {
            audioPlayer.play()
            toggleState = 2
            playBtn.setImage(UIImage(named:"pause.png"),forState:UIControlState.Normal)

        } else {
            audioPlayer.pause()
            toggleState = 1
            playBtn.setImage(UIImage(named:"play.png"),forState:UIControlState.Normal)
        }
    }


    @IBAction func play(sender: AnyObject) {
        audioPlayer.play()
    }

    @IBAction func pause(sender: AnyObject) {
        audioPlayer.pause()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func close(sender: AnyObject) {
       self.dismissViewControllerAnimated(true, completion: nil)
        audioPlayer.stop()
    }

}

以下是我已经尝试过的事情:

import UIKit
import Alamofire
import SwiftyJSON
import AVKit
import AVFoundation
import CoreMedia

class test: UIViewController {
    var audioPlayer:AVPlayer!
    var playerItem:AVPlayerItem!

   var timer:NSTimer!

    @IBOutlet weak var sermonE: UILabel!
    @IBOutlet weak var sermonL: UILabel!
    @IBOutlet weak var slider: UISlider!

    override func viewDidLoad() {
        super.viewDidLoad()


        //let playerItem:AVPlayerItem!;
        let playerURL = "example.com"
        let steamingURL:NSURL = NSURL(string:playerURL)!
        audioPlayer = AVPlayer(URL: steamingURL)


         timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("updateSlider"), userInfo: nil, repeats: true)






    }

     func updateSlider() {
        let item = audioPlayer?.currentItem

            let durationInSeconds = CMTimeGetSeconds(item!.duration)
        print(durationInSeconds)

    }

    @IBAction func ChangeAudioTime(sender: AnyObject) {

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }




    @IBAction func Play(sender: AnyObject) {
        audioPlayer.play()
    }

}

我一直在寻找几天,Apple的文档非常难以辨认。 我甚至试过

self.player.currentItem.asset.duration

来自:How to get Duration from AVPlayer (Not AVAudioPlayer)?

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

Swift 2.0

  

loadedTimeRanges 该数组包含包含CMTimeRange值的NSValue对象   指示玩家项目具有媒体数据的时间范围   一应俱全。返回的时间范围可能是不连续的。

所以我每1秒调用myplayer.getCurrentTrackDuration并注意到当我流式传输时,我在3-4秒后得到了正确的最终持续时间。

extension AVPlayer {
 //run this every 1 second of streaming (or use KVO)
 //In Http stream the duration it going to increase and probably finallize near to 7% of the total duration of the song 
 func getCurrentTrackDuration () -> Float64 {
    guard let currentItem = self.currentItem else { return 0.0 }
    guard currentItem.loadedTimeRanges.count > 0 else { return 0.0 }

    let timeInSecond = CMTimeGetSeconds((currentItem.loadedTimeRanges[0].CMTimeRangeValue).duration);

    return timeInSecond >= 0.0 ? timeInSecond : 0.0
 }
}