ios - 如何在第一首歌曲播放完毕后自动在 tableview 中播放下一首歌曲

标签 ios arrays swift uitableview xcode7

我将歌曲放入表格中,我希望当第一首歌曲结束时在表格 View 中播放下一首歌曲..>>

 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"}

当你在同一 View 中播放cel歌曲时按下

这是数组歌曲

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 实例设置委托(delegate)。
  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"}


}
}
}

关于ios - 如何在第一首歌曲播放完毕后自动在 tableview 中播放下一首歌曲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34865212/

相关文章:

arrays - 在 O(lgn) 中搜索部分排序的数组

Java 数组循环出站

php - 如何在 php 中访问一个 json 数组?

ios - 从 String 获取用于 AVPlayer 的 URL 的问题

ios - UITableViewCell、图像和纵横比

ios - 退出 iOS 中的嵌套 block 处理

iOS Autolayout 垂直等距填充父 View

iphone - 在 iOS 中使用街道地址

iphone - Youtube 视频崩溃 Xcode ios6

ios - 如何从标签栏项目中呈现 UIImagePickerController