如何修复 xcode 中的音乐重叠



我正在制作一个音乐应用程序。我通过制作 2 视图控制器而不是标签栏视图控制器来手动制作表格视图。

问题是,如果我单击表格单元格,音乐将播放。但是如果我按回键然后再次单击另一个单元格,将播放一首新歌曲,并且正在播放的当前歌曲不会停止。我想在单击新单元格后立即停止当前播放的歌曲,以便歌曲不会重叠。

我还添加了图片以更清晰地理解。希望你能帮到忙。谢谢。

这是我的视图控制器中的代码1

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 中制作了逻辑,但它不起作用。 这是我有单元格的视图控制器 这是我的视图控制器中的代码2

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() 
}
}

这是我的第二个视图控制器

最有可能的是,您的 segue 每次执行时都会初始化一个新的vc2实例(顺便说一下,这是一个糟糕的类名;请考虑将视图控制器命名为更具描述性的名称)。这样做的结果是,当您调用myconn.audioplayer.stop()时,您不会将stop()方法发送到当前正在播放的同一音频播放器,而是发送到您刚刚制作的全新播放器。

我建议改为保留一个包含对当前播放的音频播放器的引用的属性。开始播放时,将该播放器分配给属性,如果要停止,请将stop()方法发送到属性指向的对象。

最新更新