Swift實戰-QQ線上音樂(第一版)

來源:互聯網
上載者:User

標籤:

//一、*項目準備

1、QQ音樂App 介面素材:(我使用PP助手,將QQ音樂App備份,解壓ipa檔案 即可得到裡面的圖片素材)

2、豆瓣電台介面:"http://douban.fm/j/mine/playlist?channel=1"

//二、*介面布局
使用Xcode建立一個Single View Application項目,選擇Swift語言。

匯入素材圖片、在預設的ViewController視圖進行以下布局。

 

 

介面控制項不多,將幾個關鍵控制項布局就可以了。

//三、*背景模糊特效
布局好就馬上要寫代碼了,寫完將會看到一個非常漂亮的效果

首先將控制項關聯到ViewController

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方法裡,寫上模糊特效

 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)}

運行一下,看看是不是很漂亮。

//四*讓圖片旋轉起來

先把下面這個方法寫上,想看到效果就在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()    }

 

//六、請求網路資料

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

import UIKitprotocol 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 Foundationclass 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)        }    }

//七、*將請求後的第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()    }

 //八、*播放音樂

  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        }    }

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

使用到以下兩個方法

//停止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 轉載就註明來源

Swift實戰-QQ線上音樂(第一版)

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.