Swift實戰-QQ在線音樂(初版)

//1、*項目準備html

一、QQ音樂App 界面素材:(我使用PP助手,將QQ音樂App備份,解壓ipa文件 便可獲得裏面的圖片素材)json

二、豆瓣電臺接口:"http://douban.fm/j/mine/playlist?channel=1"swift

//2、*界面佈局
使用Xcode新建一個Single View Application項目,選擇Swift語言。網絡

導入素材圖片、在默認的ViewController視圖進行如下佈局。ide

 

 

界面控件很少,如圖將幾個關鍵控件佈局就能夠了。佈局

//3、*背景模糊特效
佈局好就立刻要寫代碼了,寫完將會看到一個很是漂亮的效果動畫

首先將控件關聯到ViewControllerurl

1   @IBOutlet weak var photoBorderView: UIView!
2     @IBOutlet weak var progressSlider: UISlider!
3     @IBOutlet weak var backgroundImageView: UIImageView!
4     @IBOutlet weak var photo: UIImageView!
5     @IBOutlet weak var playButton:UIButton!
6     @IBOutlet weak var titleLabel: UILabel!
7     @IBOutlet weak var artistLabel:UILabel!
8     @IBOutlet weak var playTimeLabel:UILabel!
9     @IBOutlet weak var allTimeLabel:UILabel!   

在viewDidLoad方法裏,寫上模糊特效spa

 override func viewDidLoad() {
        super.viewDidLoad()
        //將圖像變圓形
        photo.layer.cornerRadius=self.photo.frame.size.width/2.0
        photo.clipsToBounds=true
        photoBorderView.layer.cornerRadius=self.photoBorderView.frame.size.width/2.0
        photoBorderView.clipsToBounds=true
        //模糊效果
        let blurEffect=UIBlurEffect(style: UIBlurEffectStyle.Dark)
        let blureView=UIVisualEffectView(effect: blurEffect)
        blureView.frame=self.view.frame
        backgroundImageView.addSubview(blureView)
        //設置slider圖標
        progressSlider.setMinimumTrackImage(UIImage(named: "player_slider_playback_left.png"), forState: UIControlState.Normal)
        progressSlider.setMaximumTrackImage(UIImage(named: "player_slider_playback_right.png"), forState: UIControlState.Normal)
        progressSlider.setThumbImage(UIImage(named: "player_slider_playback_thumb.png"), forState: UIControlState.Normal)
}

運行一下,看看是否是很漂亮。.net

//四*讓圖片旋轉起來

先把下面這個方法寫上,想看到效果就在viewDidLoad()方法里加上 rotationAnimation()進行調用。

 //圖片旋轉動畫
    func rotationAnimation(){
        let rotation=CABasicAnimation(keyPath: "transform.rotation.z")
        rotation.timingFunction=CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
        rotation.toValue=2*M_PI
        rotation.duration=16
        rotation.repeatCount=HUGE
        rotation.autoreverses=false
        photo.layer.addAnimation(rotation, forKey: "rotationAnimation")
    }

//五*彈出播放列表頁

 新建一個PlayListView.swift和PlayListView.xib並將xib的class關聯到PlayListView

將PlayListView.xib進行佈局



//彈出方法

 //顯示
    func showPlayListView(){
        UIApplication.sharedApplication().keyWindow?.addSubview(self)
        //動畫從下向上進入
        var vbFrame:CGRect = self.viewBackground.frame
        vbFrame.origin.y=vbFrame.origin.y+vbFrame.size.height
        self.viewBackground.frame=vbFrame
        UIView.animateWithDuration(0.15, animations: { () -> Void in
            var vbFrame:CGRect = self.viewBackground.frame
            vbFrame.origin.y=vbFrame.origin.y-vbFrame.size.height
            self.viewBackground.frame=vbFrame
        });
    }

//關閉方法(將關閉按鈕,和viewTouch的點擊事件,關聯此方法)

 //關閉
    @IBAction func closePlayListView(sender: AnyObject) {
        self.removeFromSuperview()
    }

 

//彈出我關閉方法都寫好了,下面就在ViewController頁,調用此視圖讓其彈出來

 @IBAction func showPlayList(sender: UIButton) {
        NSLog("----click---")
        var playList:PlayListView=NSBundle.mainBundle().loadNibNamed("PlayListView", owner: self, options: nil).last as PlayListView
        playList.showPlayListView()
    }

 

//6、請求網絡數據

請求使用到一個封裝類:HttpProtocol.swift

import UIKit

protocol HttpProtocol{
    func didRecieveResults(results:NSDictionary)
}

class HttpController:NSObject{
    
    var delegate:HttpProtocol?
    
    func onSearch(url:String){
        NSLog("請求地址:%@", url)
        var nsUrl:NSURL=NSURL(string:url)!
        var request:NSURLRequest=NSURLRequest(URL:nsUrl)
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response:NSURLResponse!,data:NSData!,error:NSError!)->Void in
            if (data != nil){
                var jsonResult:NSDictionary=NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
                self.delegate?.didRecieveResults(jsonResult)
            }
        })
    }
}

 新建一個實體類Song.swift用來存放請求的數據

import Foundation
class Song: NSObject {
    var adtype:NSNumber = 0.0
    var aid:NSString = ""
    var album:NSString = ""
    var albumtitle:NSString = ""
    var artist:NSString = ""
    var company:NSString = ""
    var kbps:NSNumber = 0.0
    var length:NSNumber = 0.0
    var like:NSNumber = 0.0
    var monitor_url:NSString = ""
    var picture:NSString = ""
    var public_time:NSString = ""
    var rating_avg:NSString = ""
    var sha256:NSString = ""
    var sid:NSString = ""
    var songlists_count:NSNumber = 0.0
    var ssid:NSString = ""
    var subtype:NSString = ""
    var title:NSString = ""
    var url:NSString = ""
}

將請求的數據轉化了實體集合

  var eHttp:HttpController = HttpController()
 //請求網絡數據
        eHttp.delegate=self
        eHttp.onSearch("http://douban.fm/j/mine/playlist?channel=1")//華語
  //請求網絡數據結果
    func didRecieveResults(results:NSDictionary){
        NSLog("請求到的數據:%@", results)
        if (results["song"] != nil) {
            let resultData:NSArray = results["song"] as NSArray
            let list:NSMutableArray = NSMutableArray()
            
            for(var index:Int=0;index<resultData.count;index++){
                var dic:NSDictionary = resultData[index] as NSDictionary
                var song:Song=Song()
                song.setValuesForKeysWithDictionary(dic as NSDictionary)
                list.addObject(song)
            }
            self.tableData=list
            self.setCurrentSong(list[0] as Song)
        }
    }

//7、*將請求後的第1條數據設置爲當前將要播發的歌曲

綁定當前歌曲信息

  //設置當前播放的音樂
    func setCurrentSong(curSong:Song){
        currentSong=curSong
        photo.image=getImageWithUrl(currentSong.picture)
        backgroundImageView.image=photo.image
        titleLabel.text=currentSong.title
        artistLabel.text=currentSong.artist
        playButton.selected=false
        playTimeLabel.text="00:00"
        self.progressSlider.value=0.0
        self.rotationAnimation()
    }

 //8、*播放音樂

  self.audioPlayer.stop()
        self.audioPlayer.contentURL=NSURL(string:currentSong.url)
        timer?.invalidate()
        timer=NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "updateTime", userInfo: nil, repeats: true)

 

 @IBAction func playButtonClick(sender: UIButton) {
        if sender.selected {
            //暫停播放
            self.audioPlayer.pause()
            pauseLayer(photo.layer)
        }else{
            //開始/繼續播放
            self.audioPlayer.play()
            resumeLayer(photo.layer)
        }
        sender.selected = !sender.selected
    }
    
    //更新播放時間
    func updateTime(){
        let c=audioPlayer.currentPlaybackTime
         // audioPlayer.endPlaybackTime
        if c>0.0 {
            let t=audioPlayer.duration
            let p:CFloat=CFloat(c/t)
            progressSlider.value=p;
            let all:Int=Int(c)//共多少秒
            let m:Int=all % 60//
            let f:Int=Int(all/60)//
            var time=NSString(format:"%02d:%02d",f,m)
            playTimeLabel.text=time
        }
    }

//9、*當點擊播放或暫停時,須要將圖片的動畫動起來或中止動畫

使用到如下兩個方法

//中止Layer上面的動畫
    func pauseLayer(layer:CALayer){
        var pausedTime:CFTimeInterval=layer.convertTime(CACurrentMediaTime(), fromLayer: nil)
        layer.speed=0.0
        layer.timeOffset=pausedTime
    }
    
    //繼續Layer上面的動畫
    func resumeLayer(layer:CALayer){
        var pausedTime:CFTimeInterval = layer.timeOffset
        layer.speed=1.0
        layer.timeOffset=0.0
        layer.beginTime=0.0
        var timeSincePause:CFTimeInterval=layer.convertTime(CACurrentMediaTime(), fromLayer: nil)-pausedTime
        layer.beginTime=timeSincePause
    }

 

 

 最終效果:

源碼下載地址:http://download.csdn.net/detail/fangwulongtian/8565487

原文出自:http://www.cnblogs.com/wuxian/p/4394094.html 轉載就註明來源

相關文章
相關標籤/搜索