首页 > 代码库 > swift下实现网络音乐下载与播放(最通俗易懂源代码)
swift下实现网络音乐下载与播放(最通俗易懂源代码)
//
// ViewController.swift
// 网络歌曲播放
//
// Created by xx良 on 14-8-16.
// Copyright (c) 2014年 xx良. All rights reserved.
//这是我两天学习网络播放器项目的时候,总结和整理出来的代码,以后想要实现类似的功能,可以拿来就用
import UIKit
import AVFoundation
class ViewController:UIViewController {
var player=AVAudioPlayer() //========================创建音乐播放器
override func viewDidLoad() {
super.viewDidLoad()
self.onSearch("http://www.douban.com/j/app/radio/channels")//======================================================================================加载豆瓣的频道例子
self.downloadsong("http://music.baidu.com/data/music/file?link=http://yinyueshiting.baidu.com/data2/music/122112390/1201250291408075261128.mp3?xcode=709b8be58036f8a3bd0759b78c6d19683f8882ee658cd7de&song_id=120125029")//====================================================================可以通过字符串拼接得到不同的的id播放不同的歌
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func playsong(data:NSData)//音乐播放器播放
{
player=AVAudioPlayer(data: data, error:nil)
player.prepareToPlay()
print("xiaziawanle")
player.play()
}
func downloadsong(url:String)//==========================下载歌曲的方法
{
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!)->Voidin
var httpResponse=response as NSHTTPURLResponse
if (true)
{
self.playsong(data)
}
})
}
func onSearch(url:String)//=======================加载频道信息的方法
{
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!)->Voidin
var jsonResult:NSDictionary =NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error:nil) as NSDictionary
//========================我的小实验==============================================用于观察字典结构
print(jsonResult["channels"].objectAtIndex(1) )//=============可以用这个观察不同字典的guil
var obj:AnyObject=jsonResult["channels"].objectAtIndex(1)as AnyObject //
print(obj.objectForKey("name"))
var airports: Dictionary<String,String> = ["TYO":"Tokyo", "DUB":"Du,blin"]
print(airports)
//=====================================================
})
}
}
本文出自 “iamLAN” 博客,请务必保留此出处http://zhiliangzeng.blog.51cto.com/9324452/1546304
swift下实现网络音乐下载与播放(最通俗易懂源代码)