我正在获取mp3 url作为api调用的响应.我想播放那个音频,那我怎么能这样做呢?(ios swift)
这是我的回答
{ content = "En este primer programa se tratar\U00e1n asuntos tan importante como este y aquel sin descuidar un poco de todo lo dem\U00e1s"; file = "http://radio.spainmedia.es/wp-content/uploads/2015/12/ogilvy.mp3"; image = "http://radio.spainmedia.es/wp-content/uploads/2015/12/tapas.jpg"; number = 0001; subtitle = Titulareando; title = "Tapa 1"; }
这是我的代码::
@IBAction func btnplayaudio(sender: AnyObject) { let urlstring = "http://radio.spainmedia.es/wp-content/uploads/2015/12/tailtoddle_lo4.mp3" let url = NSURL(string: urlstring) print("the url = \(url!)") play(url!) } func play(url:NSURL) { print("playing \(url)") do { self.player = try AVAudioPlayer(contentsOfURL: url) player.prepareToPlay() player.volume = 1.0 player.play() } catch let error as NSError { self.player = nil print(error.localizedDescription) } catch { print("AVAudioPlayer init failed") } }
我哪里错了?
使用AVPlayer而不是AVAudioPlayer播放远程内容.根据文档,AVAudioPlayer需要mp3文件来播放音频.AVAudioPlayer不提供流媒体支持.
试试这个代码,它对我来说很好
func play(url:NSURL) { print("playing \(url)") do { let playerItem = AVPlayerItem(URL: url) self.player = try AVPlayer(playerItem:playerItem) player!.volume = 1.0 player!.play() } catch let error as NSError { self.player = nil print(error.localizedDescription) } catch { print("AVAudioPlayer init failed") } }
请记住在info.plist文件中设置App Transport Security(ATS).
NSAppTransportSecurity NSAllowsArbitraryLoads
我试过以下,
let urlstring = "http://radio.spainmedia.es/wp-content/uploads/2015/12/tailtoddle_lo4.mp3" let url = NSURL(string: urlstring) print("the url = \(url!)") downloadFileFromURL(url!)
添加以下方法,
func downloadFileFromURL(url:NSURL){ var downloadTask:NSURLSessionDownloadTask downloadTask = NSURLSession.sharedSession().downloadTaskWithURL(url, completionHandler: { [weak self](URL, response, error) -> Void in self?.play(URL) }) downloadTask.resume() }
而你的游戏方法就是这样,
func play(url:NSURL) { print("playing \(url)") do { self.player = try AVAudioPlayer(contentsOfURL: url) player.prepareToPlay() player.volume = 1.0 player.play() } catch let error as NSError { //self.player = nil print(error.localizedDescription) } catch { print("AVAudioPlayer init failed") } }
下载mp3文件,然后尝试播放它,不知何故,AVAudioPlayer不会为您下载您的mp3文件.我可以下载音频文件,玩家可以播放它.
请记住在info.plist中添加此内容,因为您从http源加载,并且您需要为iOS 9+设置以下内容
NSAllowsArbitraryLoads
由于AVPlayer
是非常有限的(例如你不能改变url
那里没有再生整体AVPlayer
我认为你应该使用AVQueuePlayer
:
来自文档:
AVQueuePlayer是AVPlayer的子类,用于按顺序播放多个项目.使用此类,您可以创建和管理由本地或逐步下载的基于文件的媒体(如QuickTime电影或MP3音频文件)以及使用HTTP Live Streaming提供的媒体组成的播放器项目队列.
所以在Swift 3中它会像这样工作:
lazy var playerQueue : AVQueuePlayer = { return AVQueuePlayer() }()
...
func playTrackOrPlaylist{ if let url = track.streamURL() { //this is an URL fetch from somewhere. In this if you make sure that URL is valid let playerItem = AVPlayerItem.init(url: url) self.playerQueue.insert(playerItem, after: nil) self.playerQueue.play() } }