我正在制作音乐应用。我通过制作一个2视图控制器而不是标签栏视图控制器手动创建一个表视图。
问题是,如果我点击一个表格单元格,音乐就会播放。但如果我按回然后再次点击另一个单元格,则会播放一首新歌并且正在播放的当前歌曲不会停止。我想在单击一个新单元格后立即停止当前播放的歌曲,以便歌曲不会重叠。
我还添加了图片以便更清楚地理解。希望你能帮忙。谢谢。
这是我的ViewController1
中的代码func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return songtitle.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.mytbl.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! tableviewcell
cell.songphoto.image = UIImage(named: img[indexPath.row])
cell.titledisplay.text = songtitle[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "go2", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let myconn = segue.destination as! vc2
let indexPath = mytbl.indexPathForSelectedRow
//This is the logic I made but it is not working
if myconn.audioplayer.isPlaying == false{
myconn.selectedsong = (indexPath?.row)!
} else {
myconn.audioplayer.stop()
myconn.selectedsong = (indexPath?.row)!
}
}
我在准备segue中制作了逻辑,但它不起作用。 This is my viewcontroller that has cells 这是我的ViewController2
中的代码var audioplayer = AVAudioPlayer()
var selectedsong = 0
override func viewDidLoad() {
super.viewDidLoad()
titlearea.text = songtitle[selectedsong]
songpic.image = UIImage(named: img[selectedsong])
do {
let audioPath = Bundle.main.path(forResource: songtitle[selectedsong], ofType: ".mp3")
try audioplayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
audioplayer.play()
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(vc2.updateProgressView), userInfo: nil, repeats: true)
}
catch
{
print("ERROR")
}
}
@IBAction func play(_ sender: UIBarButtonItem) {
if !audioplayer.isPlaying{
audioplayer.play()
}
}
答案 0 :(得分:0)
最有可能的是,你的segue正在初始化vc2
的新实例(顺便说一句,这是一个糟糕的类名;考虑每次执行时都考虑将视图控制器命名为更具描述性的)。这样做的结果是,当您拨打myconn.audioplayer.stop()
时,您并未将stop()
方法发送到当前播放的同一音频播放器,而是发送给全新的播放器你刚才做的。
我建议做的是保留包含对当前正在播放的音频播放器的引用的属性。当您开始播放时,将该播放器分配给该属性,当您想要停止时,将stop()
方法发送到该属性指向的对象。