前言
通過這文章你會學到:
- 如何使用AVAudioPlayer播放本地音樂
- app進入後臺時,仍能播放音樂,並且能在控制檯控制播放暫停
- 提供鎖屏下的信息,例如圖片
- 將文字和圖片合成爲新的圖片,實現類似 網易雲 鎖屏下輪播歌詞的原理。
播放音樂
使用AVFoundation
在文件任意地方寫下下面代碼,然後執行playBackgroundMusic("音樂1")
就可以播放音樂了
import AVFoundation
var backgroundMusicPlayer: AVAudioPlayer!
func playBackgroundMusic(filename: String) {
//獲取播放文件的位置,通過文件名和後綴
let url = NSBundle.mainBundle().URLForResource(filename, withExtension: "mp3")
//如果找不到文件則返回錯誤
if (url == nil) {
println("Could not find the file \(filename)")
}
var error: NSError? = nil
//將播放文件賦值給播放器
backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
//如果建立不了播放器則,提錯
if backgroundMusicPlayer == nil {
println("Could not create audio player: \(error!)")
return
}
//負值表示單曲循環
backgroundMusicPlayer.numberOfLoops = -1
backgroundMusicPlayer.prepareToPlay()
backgroundMusicPlayer.play()
}
playBackgroundMusic("大開眼界")//播放`大開眼界.mp3`
後臺播放音樂並操作
首先在info.plist
添加如圖標註的字符串
就是在函數playBackgroundMusic(filename: String)
加上以下代碼,就可以實現後臺播放:
do {
//播放器獨佔後臺,其它音樂會停止
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
}catch{
print(error)
}
接着則是後臺時控制
首先在viewDidLoad
設置app接收remote event並且將viewController成爲FirstResponder.
那麼添加如下代碼在viewDidload
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
self.becomeFirstResponder()
並且在viewController
覆蓋canBecomeFirstResponder
override func canBecomeFirstResponder() -> Bool {
return true
}
在viewWillDispper
添加代碼
UIApplication.sharedApplication().resignFirstResponder()
self.resignFirstResponder()
最後通過viewController處理事件,在viewController添加如下代碼。
就能在程序切換到後臺時不結束音樂。並實現如圖中按下播放按鍵暫停或者播發音樂。
override func remoteControlReceivedWithEvent(event: UIEvent?) {
if event == nil {
return
}
//播放或者暫停按鈕按下時執行相應操作
if event?.type == UIEventType.RemoteControl{
switch(event!.subtype){
case .RemoteControlPlay:
backgroundMusicPlayer.play()
case .RemoteControlPause:
backgroundMusicPlayer.pause()
default:
print(event!.subtype)
}
}
}
這樣就能響應事件了。
鎖屏下的音樂信息
使用MPNowPlayingInfoCenter
import MediaPlayer
func configNowPlaying(currentTime:NSTimeInterval,fireTime:NSTimeInterval){
let mpPlayer = MPNowPlayingInfoCenter.defaultCenter()
let image25 = UIImage(named:"25image")!
//設置:歌名,封面圖片,現在的所在播放時間,播放速度,音樂的時長
let tmpPlayingInfo = [ MPMediaItemPropertyTitle : "25min",
MPMediaItemPropertyArtwork : MPMediaItemArtwork(image: image25) ,
MPNowPlayingInfoPropertyElapsedPlaybackTime : NSNumber(double: currentTime),
MPNowPlayingInfoPropertyPlaybackRate : 1.0,
MPMediaItemPropertyPlaybackDuration: fireTime
]
//將設置好的dict設置到infoCenter
mpPlayer.nowPlayingInfo = tmpPlayingInfo
}
鎖屏下合成圖片
效果:
實現思路,就是通過NSTimer
不斷在後臺每一秒合成圖片和文字。
然後將合成後的圖片如上函數configNowPlaying(_::)
賦值給nowPlayingInfo
的封面圖片
那麼合成圖片的代碼
func textToImage(drawText: NSString, inImage: UIImage)->UIImage{
// 設置字體格式
let textFont: UIFont = UIFont(name: "Helvetica Bold", size: textSize)!
//用圖片大小設置image context的大小
UIGraphicsBeginImageContext(inImage.size)
//將圖片畫進去
inImage.drawInRect(CGRectMake(0, 0, inImage.size.width, inImage.size.height))
//使用函數drawString,將文字畫進去。(下面會有這個自定義函數)
drawSting(drawText, withFont: textFont, inRect: CGRectMake(0, 0, inImage.size.width, inImage.size.height))
// 然後獲取描繪好的圖片
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
// 結束imageContext描繪
UIGraphicsEndImageContext()
//將合成圖片傳遞
return newImage
}
以下是居中描繪文字的函數drawString
func drawSting(s:NSString,withFont font:UIFont,inRect contextRect: CGRect){
//設置文字顯示,居中
let paragraphStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.lineBreakMode = NSLineBreakMode.ByTruncatingTail
paragraphStyle.alignment = NSTextAlignment.Center
//設置文字屬性,待會描繪文字時用
let attr = [
NSFontAttributeName : font,
NSForegroundColorAttributeName : UIColor.blackColor(),
NSParagraphStyleAttributeName : paragraphStyle
]
//將字符串賦予屬性
let size = s.sizeWithAttributes(attr)
//設置文字局中的位置
let xOffset = contextRect.origin.x + floor((contextRect.size.width - size.width) / 2)
let yOffset = contextRect.origin.y + floor((contextRect.size.height - size.height) / 2)
let textRect = CGRectMake(xOffset, yOffset, size.width, size.height)
//描繪文字
s.drawInRect(textRect, withAttributes: attr)
}
let whiteImage = UIImage(named:"whiteImage")!
let newImage = textToImage("24:55", inImage: whiteImage)//效果如下
我這裏是用白色的圖片加上字符串實現的。
同理要實現網易雲的那種效果則只需將白底的圖片換成封面圖加上歌詞就可以了。
最後
本教程基本上就實現一個播放器的基本功能。
(END and Thank U)
參考鏈接:
後臺播放
更多remote中控制的做法