我正在开发一个音乐流媒体应用程序,可以从数据库中传输音乐。我的代码动态地为我的数据库中的每首歌创建按钮,当点击这些按钮时,它们播放mp3文件。但是,我无法弄清楚如何暂停音乐,当我不止一次点击这些按钮时,这首歌就会自动播放,因此可以同时播放两首歌曲。我已经尝试过player.pause()等等,但没有什么能阻止音乐播放/流式传输和循环播放。
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()
}
}
}
}
答案 0 :(得分:2)
这里的问题是,每次单击按钮并且不保留对它的引用时,您将创建一个新的播放器。所以你不能停止/暂停甚至访问播放器。
您应该只在视图中有一个玩家,并且一次只能播放一个项目,您可以管理一个播放列表&#39;使用AVQueuePlayer播放的项目,以便您可以按顺序播放项目。
AVQueuePlayer是AVPlayer的子类,因此您应该仍然可以调用所有常用功能,例如暂停/停止。
使用一系列项目初始化它(它可以只是一个项目开始),然后再添加项目。
但是你要解决这个问题,你不应该有这个
let player = AVPlayer(url: URL! as URL)
在函数中,在视图中有一个播放器或AVQueuePlayer,然后您可以在以后引用它。 self.player.pause()