下文主要给大家带来swift下如何实现网络音乐下载与播放,希望这些文字能够带给大家实际用处,这也是我编辑swift下如何实现网络音乐下载与播放这篇文章的主要目的。好了,废话不多说,大家直接看下文吧。

importUIKit

importAVFoundation

classViewController:UIViewController{

varplayer=AVAudioPlayer() //========================创建音乐播放器

overridefuncviewDidLoad() {

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播放不同的歌

}

overridefuncdidReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

}

funcplaysong(data:NSData)//音乐播放器播放

{

player=AVAudioPlayer(data: data, error:nil)

player.prepareToPlay()

print("xiaziawanle")

player.play()

}

funcdownloadsong(url:String)//==========================下载歌曲的方法

{

varnsUrl:NSURL=NSURL(string:url)

varrequest:NSURLRequest=NSURLRequest(URL:nsUrl)

//后面是一个闭包方法

NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue.mainQueue(), completionHandler:

{(response:NSURLResponse!,data:NSData!,error:NSError!)->Voidin

varhttpResponse=responseasNSHTTPURLResponse

if(true)

{

self.playsong(data)


}


})

}


funconSearch(url:String)//=======================加载频道信息的方法

{

varnsUrl:NSURL=NSURL(string:url)

varrequest:NSURLRequest=NSURLRequest(URL:nsUrl)

NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue.mainQueue(), completionHandler:

{(response:NSURLResponse!,data:NSData!,error:NSError!)->Voidin

varjsonResult:NSDictionary=NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error:nil)asNSDictionary

//========================我的小实验==============================================用于观察字典结构

print(jsonResult["channels"].objectAtIndex(1) )//=============可以用这个观察不同字典的guil

varobj:AnyObject=jsonResult["channels"].objectAtIndex(1)asAnyObject//

print(obj.objectForKey("name"))

varairports:Dictionary<String,String> = ["TYO":"Tokyo","DUB":"Du,blin"]

print(airports)

//=====================================================

对于以上关于swift下如何实现网络音乐下载与播放,大家是不是觉得非常有帮助。如果需要了解更多内容,请继续关注我们的行业资讯,相信你会喜欢上这些内容的。