在 iOS 的表格视图中播放歌曲

Posted

技术标签:

【中文标题】在 iOS 的表格视图中播放歌曲【英文标题】:Play Song displayed in the table view in iOS 【发布时间】:2016-03-08 17:53:02 【问题描述】:

我已在表格视图中显示了 iTunes 音乐库中的所有歌曲。现在我想在用户点击后立即在表格视图中播放选定的歌曲。

这是我的代码:

import UIKit
import MediaPlayer

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource 
    @IBOutlet var table: UITableView!

    //Create an array with some elements for the table view rows
    var myMusicPlayer = MPMusicPlayerController()
    var allSongsArray: [MPMediaItem]!
    let songsQuery = MPMediaQuery.songsQuery()
    var abcArray = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z", "#"]

    //Define the amount of sections in table view
    func numberOfSectionsInTableView(tableView: UITableView) -> Int 
        return abcArray.count
    

    //Assign the amount of elements in the array to the amount of rows in one section
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
       return allSongsArray.count
    

    //Set up each element in abcArray as title for section
    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? 
        return self.abcArray[section] as String
    

    //Set up the Index Search
    func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? 
        return abcArray
    

    //Assign each element in the array a row in table view
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 

        var cell = tableView.dequeueReusableCellWithIdentifier("cell")
        var items = allSongsArray[indexPath.row]

        cell?.textLabel?.text = items.title
        cell?.detailTextLabel?.text = items.artist
        var imageSize = CGSizeMake(100, 100)
        cell?.imageView?.image = items.artwork?.imageWithSize(imageSize)

        return cell!
    

    override func viewDidLoad() 
        super.viewDidLoad()

        self.allSongsArray = songsQuery.items! as [MPMediaItem]
    

    override func didReceiveMemoryWarning() 
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    

【问题讨论】:

你有什么问题?你有什么问题?您是否尝试过任何代码来播放歌曲或处理行选择? 其实我也不知道,哪段代码适合播放歌曲...? 【参考方案1】:

使用此参考

import UIKit
import AVFoundation



class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource 

    var player:AVAudioPlayer?

    var audio = ["song1","song2","song3","song4"]
    override func viewDidLoad() 
        super.viewDidLoad()
        let table:UITableView = UITableView()
        let frame = bounds()
        table.frame = CGRectMake(0.0, 64.0, frame.size.width, frame.size.height - 64.0)
        table.delegate = self
        table.dataSource = self
        table.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
        self.view .addSubview(table)

        // Do any additional setup after loading the view, typically from a nib.
    

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 

        return audio.count
    

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 

        let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
        cell.textLabel?.text = self.audio[indexPath.row]
        return cell
    

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

//        let details = PlayerViewController(nibName:"PlayerViewController",bundle: nil)
//        details.song = self.audio[indexPath.row] as String?
//        self.navigationController!.pushViewController(details, animated: true)

        player = setupAudioPlayerWithFile(audio[indexPath.row], type: "mp3")
        player?.play()

    


    func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer?  
        //1
        let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
        let url = NSURL.fileURLWithPath(path!)

        //2
        var audioPlayer:AVAudioPlayer?

        // 3
        do 
            try audioPlayer = AVAudioPlayer(contentsOfURL: url)
         catch 
            print("Player not available")
        

        return audioPlayer
    




    func bounds() -> CGRect
    
      return UIScreen.mainScreen().bounds
    

    override func didReceiveMemoryWarning() 
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    



【讨论】:

以上是关于在 iOS 的表格视图中播放歌曲的主要内容,如果未能解决你的问题,请参考以下文章

如何让 avaudioplayer 在点击新闻歌曲时停止播放上一首歌曲?

如何在列表视图中添加最近播放的歌曲?

由于表格视图中可重复使用的单元格,当它滚动到视图之外时会丢失 Youtube 播放器

ios在内存中保持视图

当我单击媒体播放器中的列表视图时,正在播放多首歌曲

从列表视图中单击歌曲后,新活动正在打开但歌曲未播放