音視頻相關:
1.語音合成器
let synthesizer = AVSpeechSynthesizer()
let utterance = AVSpeechUtterance(string:”需要讀的內容”)
synthesizer.speakUtterance(utterance)
2.音頻播放器
需要在類中聲明一個屬性
var player:AVAudioPlayer!
a.獲取音頻的路徑
let url = NSBundle.mainBundle().URLForResource("月半小夜曲", withExtension: ".mp3")
b. player = try! AVAudioPlayer(contentsOfURL: url)
c.其他設置
// 緩沖音樂文件(播放音樂之前先緩沖)
player.prepareToPlay()
// 設置播放音量(0~1,可以調大于1,但是聲音也有可能失真)
player.volume = 0.5
// 指定從200開始播放
// player.currentTime = 200
// 允許變速播放
player.enableRate = true
// 設置倍速()
player.rate = 1.2
// 設置無限循環播放(負數為無限)
player.numberOfLoops = -1
// 播放
player.play()
//當前播放時間點
print(player.currentTime)
// 音樂的時長
print(player.duration)
2.1、想要設置后臺播放的話,必須設置會話還有設置Xcode中Capabilities中BackgrounndModes這一選項,在第一行打鉤
創建一個音頻會話對象設置支持后臺播放(Xcode的設置和這個代碼缺一不可)
//創建會話
let session = AVAudioSession()
// 支持后臺播放
do {
//激活會話
try session.setActive(true)
//設置音頻會話的類別(支持后臺播放的類別)
try session.setCategory(AVAudioSessionCategoryPlayback, withOptions: [])
} catch {
print("不支持后臺播放")
}
2.2、 顯示音頻的內容
if let url = NSBundle.mainBundle().URLForResource("月半小夜曲", withExtension: ".mp3"{
//通過創建AVURLAsset對象用來獲取音視頻文件的元數據
let assets = AVURLAsset(URL: url)
//dataItem元數據項
print(assets.metadata)
for dataItem in assets.metadata
{
if let key = dataItem.commonKey
{
switch key
{
case "artist":
artistLabel.text = dataItem.value as? String
case "title":
titleLabel.text = dataItem.value as?String
case "albumName":
albumLabel.text = dataItem.value as? String
case "artwork":
if let data = dataItem.value as? NSData
{
coverImageView.image = UIImage(data: data)
}
default: break
}
}
3.錄音
import UIKit
import AVFoundation
class ViewController: UIViewController {
//不能放到方法里,,不然沒人接管他的生命周期
var recorder: AVAudioRecorder?
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func startRecordd(sender: UIButton) {
//
//如果為空就創建recorder
if recorder == nil
{
sender.setTitle("結束錄音", forState: .Normal)
//字典
let mySettings: [String:AnyObject] = [
//設置錄音質量
AVEncoderAudioQualityKey:AVAudioQuality.Low.rawValue,
//比特率(16為字符串常量)
AVEncoderBitRateKey: 16,
//聲道數
AVNumberOfChannelsKey:2,
//采樣頻率
AVSampleRateKey:44100
]
// 拿到沙盒路徑(把當前路徑存到沙盒中)
let filePath = NSHomeDirectory().stringByAppendingString("/Documents/test.caf")
print(filePath)
// 創建URL
let url = NSURL(fileURLWithPath: filePath)
self.recorder = try! AVAudioRecorder(URL: url, settings: mySettings)
//開始錄音
recorder?.record()
} else {
sender.setTitle("開始錄音", forState: .Normal)
recorder?.stop()
recorder = nil
}
}
}
4.播放視頻
import UIKit
import AVFoundation
import AVKit
class ViewController: UIViewController {
// var player:AVPlayer!
var timer:NSTimer?
var isPlaying = false
override func viewDidLoad() {
super.viewDidLoad()
//添加通知觀察者(觀察視頻播放完就停止播放)
//參數2:選擇器接受到通知,就會停止播放
//參數3:通知
//參數4:nil接受所有的對象
NSNotificationCenter.defaultCenter().addObserver(self, selector: "stop:", name: AVPlayerItemDidPlayToEndTimeNotification, object: nil)
//顯示出來視頻
//方式1:
// let layer = AVPlayerLayer(player: player)
// layer.frame = self.view.bounds
// //不能直接加到self.view
// self.view.layer.addSublayer(layer)
// player.play()
}
func stop(sender:NSNotification)
{
//播放完后自動停止
self.dismissViewControllerAnimated(true, completion: nil)
isPlaying = false
}
//點擊屏幕開始播放
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
//一個視圖控制器中不能模態多個視圖控制器,,模態出來第一個之后就不會模態的第二個了(程序不會崩潰,)
//方式2:
if let url = NSBundle.mainBundle().URLForResource("birds.mp4", withExtension: nil) {
//player已經被playerVC接管了,不會被釋放掉了
let player = AVPlayer(URL: url)
// AVPlayerViewController可以簡化AVPlayer的使用
// AVPlayer負責控制視頻的播放停止等
// AVPlayerViewController負責顯示和提供播放控件
// AVPlayerViewController是MPMoviePlayerController的替代品,AVPlayerViewController針對iPad還提供了畫中畫功能,,他們是AVKit框架下高度封裝的工具類
// 如果希望自己定制播放控件那么可以直接使用AVPlayer
// 先用AVPlayer將視頻顯示出來,
// 然后用按鈕,滑條,進度條之類的東西來自己的定制播放控件
let playerVC = AVPlayerViewController()
playerVC.player = player
//
self.presentViewController(playerVC
, animated: true,completion: {
//出來之后就自動播放
player.play()
})
}
}
deinit {
//手動移除觀察者
//移除觀察者后一定要記得手動移除通知觀察者否則有 內存泄漏的風險
NSNotificationCenter.defaultCenter().removeObserver(self)
//使用計時器的對象后一定要在deinit中使其失效以避免內存泄漏
timer?.invalidate()
timer = nil
}
}
5.地圖
import UIKit
import MapKit
class ViewController: UIViewController,CLLocationManagerDelegate {
//蘋果原生的地圖
var mapView: MKMapView!
//核心定位(定位管理器)
var locationManager: CLLocationManager!
@IBOutlet weak var mapTypeSeg: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
// 創建定位管理器
locationManager = CLLocationManager()
// 綁定事件委托
locationManager.delegate = self
// 設置精確度(精度越高耗電越大 )
// 設置導航使用kCLLocationAccuracyBestForNavigation最佳
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
// 距離過濾器(十米之內不用重新定位)
locationManager.distanceFilter = 10
/*
case Standard
case Satellite
case Hybrid 混合地圖
@available(iOS 9.0, *)
case SatelliteFlyover
@available(iOS 9.0, *)
case HybridFlyover
*/
// 地圖已經顯示出來
mapView = MKMapView(frame: self.view.bounds)
//
mapView.mapType = .SatelliteFlyover //混合地圖
//顯示交通狀況
mapView.showsTraffic = true
self.view.addSubview(mapView)
//將分段控件放置到整個視圖層次結構的最頂層
self.view.bringSubviewToFront(mapTypeSeg)
// 創建坐標(經度和緯度)
// 參數1:緯度 參數2:經度
let coordinate = CLLocationCoordinate2DMake(30.6621, 104.041367)
// 設置跨度
let span = MKCoordinateSpanMake(0.01, 0.01)
// 參數1:地圖中心點的經緯度坐標
// 參數2:地圖跨度(經緯度跨度)
// 設置地圖的中心點(設置區域)
let region = MKCoordinateRegionMake(coordinate, span)
// 設置地圖中心點地區
mapView.setRegion(region, animated: true)
// 判斷請求授權
// 獲取定位服務的授權狀態
let status = CLLocationManager.authorizationStatus()
// 尚未沒有授權
if status == .NotDetermined {
// 請求授權一直使用定位服務(可以在后臺使用定位服務)
locationManager.requestAlwaysAuthorization()
// 請求授權在應用程序使用期間開啟定位服務
// locationManager.requestWhenInUseAuthorization()
//之前已拒絕授權
} else if status == .Denied {
//提示用戶跳轉設置開啟定位服務
} else {
//開始更新位置信息
locationManager.startUpdatingLocation()
//在地圖上顯示用戶當前位置
mapView.showsUserLocation = true
}
}
@IBAction func segAction(sender: UISegmentedControl) {
//Standard:標準地圖, Satellite:衛星地圖 Hybrid:混合地圖
let typeArray = [MKMapType.Standard,.Satellite,.Hybrid]
mapView.mapType = typeArray[sender.selectedSegmentIndex]
}
}
extension ViewController
{
//定位授權狀態被改變時要執行的方法
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
//如果請求定位授權成功就開始更新位置信息并 在地圖上顯示用戶位置
if status == .AuthorizedAlways || status == .AuthorizedWhenInUse
{
manager.startUpdatingLocation()
mapView.showsUserLocation = true
}
}
//更新位置信息后要執行的方法
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//
if let location = locations.first
{
let span = MKCoordinateSpanMake(0.01, 0.01)
// 參數1:地圖中心點的經緯度坐標
// 參數2:地圖跨度(經緯度跨度)
let region = MKCoordinateRegionMake(location.coordinate, span)
//設置地區
mapView.setRegion(region, animated: true)
}
}
}