远程的MP3文件需要花费很多时间在迅速的ios中播放

我有麻烦了。 我想在我的应用程序中播放一个远程的MP3文件。 但需要花费大量的时间(大约5-6分钟)的MP3文件播放。 为什么?

任何人都可以build议我该怎么做?

import UIKit import AVFoundation class TestViewController: UIViewController, AVAudioPlayerDelegate { var player:AVAudioPlayer = AVAudioPlayer() override func viewDidLoad() { super.viewDidLoad() } @IBAction func play(sender: AnyObject) { let url = "http://www.example.com/song.mp3" let fileURL = NSURL(string: url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())) let soundData = NSData.dataWithContentsOfURL(fileURL, options: nil, error: nil) var error: NSError? self.player = AVAudioPlayer(data: soundData, error: &error) if player == nil { if let e = error { println(e.localizedDescription) } } player.volume = 1.0 player.delegate = self player.prepareToPlay() player.play() } } 

提前致谢。

使用AVPlayer而不是AVAudioPlayer来传输audio。 它可以像这样简单 –

 let urlString = "http://www.example.com/song.mp3" let url = NSURL(string: urlString) var avPlayer = AVPlayer(URL: url) avPlayer.play() 

您还可以在AVPlayer.status属性上设置观察者来pipe理其更改状态。 签出: https : //stackoverflow.com/a/13156942/2484290 (目标c)

当然AVPlayer文档在这里: https : //developer.apple.com/LIBRARY/ios/documentation/AVFoundation/Reference/AVPlayer_Class/index.html#//apple_ref/occ/cl/AVPlayer

它可能迟到了。 是。 什么@lemon酸橙柚说过。 您应该使用AVPlayer而不是AVAudioPlayer。

你也可以使用MediaPlayer。

 import UIKit import MediaPlayer @IBAction func playSong(sender: AnyObject) { print("Song") self.playAudio("yourAudioURL.mp3") } func playAudio(URL:String){ let movieurl:NSURL? = NSURL(string: "\(URL)") if movieurl != nil { self.movie = MPMoviePlayerViewController(contentURL: movieurl!) } if self.movie != nil { self.presentViewController(self.movie!, animated: true, completion: nil) self.movie?.moviePlayer.play() } } 

这很慢,因为您的程序在开始播放之前下载了所有歌曲