2017-03-03 37 views
-6

我目前正在爲iOS的音頻流應用程序,我是新來的迅速。我能夠拉動目前使用JSON序列從數據庫中的歌曲,然後爲每一個人創造的歌曲按鈕和播放它們,但我無法弄清楚如何暫停呢?暫停JSON數組

這裏是我的代碼:

import UIKit 
import AVKit 
import AVFoundation 


class ViewController: UIViewController { 

    var songArray: [Array<String>] = [] //array to contain song names and filepaths 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 

     //connect to website 
     let url = URL(string:"http://cgi.soic.indiana.edu/~team22/SongData.php") 
     let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in 
      if error != nil 
      { 
       print("error") 
      } 
      else 
      { 
       if let content = data 
       { 
        do 
        { 
         //download JSON data from php page, display data 
         let JSON = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as! [[String]] 
         print(JSON) 

         //Make buttons with JSON array 
         var buttonY: CGFloat = 20 
         for song in JSON { 
          //add information to array 
          self.songArray.append(song) 
          let SongButton = UIButton(frame: CGRect(x: 50, y: buttonY, width: 250, height: 30)) 
          buttonY = buttonY + 50 // 50px spacing 

          SongButton.layer.cornerRadius = 10 //Edge formatting for buttons 

          SongButton.backgroundColor = UIColor.darkGray //Color for buttons 

          SongButton.setTitle("\(song[0])", for: UIControlState.normal) //button title 

          SongButton.titleLabel?.text = "\(song[0])" // set title label 

          SongButton.addTarget(self,action: #selector(self.songButtonPressed(_:)), for: UIControlEvents.touchUpInside) //button press/response 

          self.view.addSubview(SongButton) // adds buttons to view 
         } 
        } 
        catch 
        { 

        } 
       } 
      } 
     } 
     task.resume() 
     print(songArray) 

    } 


    func songButtonPressed(_ sender:UIButton!) { // Streaming function for buttons when pressed 
     for song in songArray { 
      if "\(song[0])" == sender.titleLabel?.text { //compare loop element to name of button pressed 



       let URL = NSURL(string: song[1]) //plug loop element into audio player 
       let player = AVPlayer(url: URL! as URL) 
       let playerLayer = AVPlayerLayer(player: player) 
       playerLayer.frame = self.view.bounds 
       self.view.layer.addSublayer(playerLayer) 
       player.play() 
      } 
     } 
    } 
} 
+6

這是沒有任何關係的「暫停JSON數組」這是暫停一些媒體做 – Fogmeister

+0

谷歌「暫停音頻迅速IOS」。 –

回答

0

去蘋果文檔和查找AVPlayer。有一個.pause()函數。就那麼簡單。你的另外一個問題是,你不必訪問您songButtonPressed範圍之外的該玩家的任何方式,所以你需要一個變量在你的viewController(即低於你var songArray...,這樣當有人按下暫停按鈕,你可以說self.player.pause()

鏈接到文檔:https://developer.apple.com/reference/avfoundation/avplayer