2017-08-31 35 views
-2

我正在製作音樂應用程序。我通過製作2視圖控制器而不是標籤欄視圖控制器來手動創建表格視圖。如何修復xcode中的音樂重疊問題

問題是,如果我點擊表格單元格,音樂將播放。但是,如果我按回來,然後再次單擊另一個單元格,一首新歌曲將播放,當前正在播放的歌曲不會停止。當我點擊一個新單元格時,我想立即停止當前正在播放的歌曲,以便歌曲不會重疊。

我還添加了更清晰的圖片。希望你能幫助。謝謝。

這是代碼從我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)! 
    } 
} 

我所做的邏輯在那裏我準備賽格瑞內,但它無法正常工作。 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() 
    } 
} 

This is my second Viewcontroller

+0

請參閱[如何創建一個最小,完整和可驗證的示例](https://stackoverflow.com/help/mcve)並重新設置您的代碼的格式,在當前狀態下,它是完全不可讀的。 –

+0

完成編輯。 im抱歉 –

+0

我後退按鈕中的唯一代碼是dismissanimation視圖控制器代碼。 –

回答

0

最有可能的,你賽格瑞正在初始化的vc2一個新實例(這是一個可怕的類名,順便;考慮命名您的看法控制器更具描述性)每次執行。這樣做的結果是,當您撥打myconn.audioplayer.stop()時,您不會將stop()方法發送給當前正在播放的同一個音頻播放器,而是發送給您剛製作的全新音頻播放器。

我推薦做的是保持一個包含當前播放音頻播放器的引用的屬性。當您開始播放時,將該播放器分配給該媒體資源,當您想停止時,請將stop()方法發送給該媒體資源所指向的對象。