繁体   English   中英

当第一首歌结束后,如何在表视图中自动播放下一首歌

[英]How to play the next song in tableview automatically when first song finish

我把歌曲放到一张桌子里,我想等第一首歌结束后再在桌子上播放下一首歌.. >>

 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {


    if  let audio=NSBundle.mainBundle().pathForResource( elmp3[indexPath.row] , ofType: "mp3")
    {
        let url=NSURL (fileURLWithPath: audio)

        do {


            player = try AVAudioPlayer (contentsOfURL: url)

        }

        catch{"erorr"}

当您按cel歌曲以相同视图播放时

这是Array歌曲

var elmp3 = ["001","002","003","004","005","006","007","008","009","010","011","012","013","014","015","016","017","018","019","020","021","022","023","024","025","026","027","028","029"]
  1. selectedIndex创建一个实例变量。
  2. didSelectRowAtIndexpath:方法中将selectedIndex更新为indexPath.row。
  3. 实现AVAudioPlayerDelegate方法并为AVAudioPlayer实例设置委托。
  4. 然后在audioPlayerDidFinishPlaying:回调方法中,增加selectedIndex并播放列表中的下一个音频。

步骤如下:

1。

var selectedIndex:Int = 0

2。

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

//Set selected index
self.selectedIndex = indexPath.row

//get audio file URL at index
if  let audio=NSBundle.mainBundle().pathForResource( elmp3[self.selectedIndex] , ofType: "mp3")
{
    let url=NSURL (fileURLWithPath: audio)

    do {


        player = try AVAudioPlayer (contentsOfURL: url)
        //Set delegate for AVAudioPlayer
        player.delegate = self

    }

    catch{"error"}

 }

3。

class AudioPlayerController:UIViewController, AVAudioPlayerDelegate{

func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer,
                         successfully flag: Bool){

if flag == true && self.selectedIndex < elmp3.count{

//Increment current index
++ self.selectedIndex
 //Load audio at current index and play
 if  let audio=NSBundle.mainBundle().pathForResource( elmp3[self.selectedIndex] , ofType: "mp3")
{
    let url=NSURL (fileURLWithPath: audio)

    do {
        player = try AVAudioPlayer (contentsOfURL: url)
        player.delegate = self

    }

    catch{"error"}


}
}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM