AVPlayer,AVAudioPlayer,语音合成

AVPlayer是AV Foundation框架中的类。可以使用AVPlayer来播放视频,AVPlayer只管播放视频,将视频显示出来时AVPlayerLayer的工作。而要向视图添加AVPlayerLayer就需要视图必须有一个CALayer来使AVPlayerLayer来作为其子层。在IOS中所有的UIView都有一个CALayer,而OS X中NSView在默认情况下是不使用CALayer的。要在OS X中开启CALayer选中要打开CALayer的视图,选择View Effects Inspector将Core Animation Layer中列出来的视图勾选上即可。
AV Foundation还支持声音的播放和对视频音频的采集

    @IBOutlet weak var playerView: NSView!
    
    @IBAction func play(sender: NSButton) {
        self.player?.play()
    }
    @IBAction func playSlow(sender: NSButton) {
        self.player?.rate = 0.25
    }
    @IBAction func playBack(sender: NSButton) {
        self.player?.seekToTime(kCMTimeZero)
    }
    var player: AVPlayer?
    override func viewDidLoad() {
        super.viewDidLoad()
        if let contentURL = NSBundle.mainBundle().URLForResource("TestVideo", withExtension: "m4v") {
            player = AVPlayer(URL: contentURL)
        }
        let playerLayer = AVPlayerLayer(player: player)
        self.playerView.layer?.addSublayer(playerLayer)
        playerLayer.frame = self.playerView.bounds
        playerLayer.autoresizingMask = CAAutoresizingMask.LayerWidthSizable //CAAutoresizingMask.LayerHeightSizable
        self.player?.actionAtItemEnd = AVPlayerActionAtItemEnd.None
    }

其实有更简单的框架。。。

只不过只支持OS X 10.9 和 IOS 8及以后的版本。
在OS X上,你可以直接使用AVPlayerView,将AVPlayerView放在你想播放视频的地方。

@IBOutlet weak var playerView: AVPlayerView!
override func viewDidLoad() {
    super.viewDidLoad()
    if let contentURL = NSBundle.mainBundle().URLForResource("TestVideo", withExtension: "m4v") {
        self.playerView.player = AVPlayer(URL: contentURL)
    }
}

在IOS上把一个AVPlayerViewController放在你想放置视频的地方,引入AVKit和 AV Foundation框架,只用下面的配置即可。

let videoURL = NSBundle.mainBundle().URLForResource("TestVideo", withExtension: "m4v")
let videoView = segue.destinationViewController as! AVPlayerViewController
videoView.player = AVPlayer(URL: videoURL!)

AVAudioPlayer

它的使用和AVPlayer很像

let audioURL = NSBundle.mainBundle().URLForResource("a", withExtension: "wav")
let audioPlayer = try? AVAudioPlayer(contentsOfURL: audioURL!)
audioPlayer!.play()
audioPlayer?.volume = 0.5
audioPlayer?.numberOfLoops = -1//0:一次,1:两次
audioPlayer?.currentTime = 0

语音合成

//语音合成
let synthesizer = AVSpeechSynthesizer()
//要读出的字符串
let utteranceString = "I am lion"
let utterance = AVSpeechUtterance(string: utteranceString)
utterance.rate = 0.175
synthesizer.speakUtterance(utterance)

你可能感兴趣的:(AVPlayer,AVAudioPlayer,语音合成)