開発メモ

開発関係のメモをいろいろと。たぶん。

セルの選択で対応する曲を再生

動作を確認した環境

環境 情報
Xcode 6.3.2 (6D2105)
iOS 8.3
Swift 1.2
Date 2015/6/7

セルの選択で対応する曲を再生

せっかくテーブルビューにプレイリストを表示しているので、セルを選択して曲を再生できるように修正。

とりあえず、didSelectRowAtIndexPathに対応する。この辺りの処理は、UITableViewを使う時のお約束的な実装。

class PlaylistTableAdmin: NSObject, UITableViewDelegate, UITableViewDataSource {

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

        // タッチされたセルの曲を再生
        g_musicPlayer.play(indexPath.row)

        // 選択を解除しておく
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }

    ※関係ない部分は省略
}

再生側の実装はこんな感じ。

class SK4MusicPlayerAdmin: NSObject {

    /// プレイリストの指定された曲を再生
    func play(no: Int) {
        if 0 <= no && no < playlist.count {
            player.nowPlayingItem = playlist[no]
            play()
        }
    }

    ※関係ない部分は省略
}

ここまでの対応で指定した曲を再生できるようになるんだけど・・・ どの曲が再生されてるのかわかりにくいので、テーブルビューにも反映されるように修正。

とりあえず、再生中の曲はアートワークの部分に専用のイメージを表示するようにしてみた。

class PlaylistTableAdmin: NSObject, UITableViewDelegate, UITableViewDataSource {

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cellId = "Cell"

        let cell = tableView.dequeueReusableCellWithIdentifier(cellId, forIndexPath: indexPath) as! UITableViewCell
        let item = g_musicPlayer.playlist[indexPath.row]

        cell.textLabel?.text = item.title
        cell.detailTextLabel?.text = "\(item.artist) - \(item.albumTitle)"
        cell.imageView?.image = getArtworkImage(item)

        return cell
    }

    /// アートワークで使用するイメージを取得
    func getArtworkImage(item: MPMediaItem) -> UIImage? {

        // 再生中の曲の場合は専用のイメージを返す
        if g_musicPlayer.nowPlayingItem == item {
            return UIImage(named: "playing")
        }

        // 曲に設定されてるアートワークを取得
        let size = CGSize(width: 40, height: 40)
        if let artwork = item.artwork {
            return artwork.imageWithSize(size)
        }

        return nil
    }

    ※関係ない部分は省略
}

アートワークを取得する部分を関数にして、再生中の曲の場合は専用のイメージを返すようにしただけ。再生中で使うイメージはgimpで適当に作成。

あとは曲の変更に応じてテーブルビューも更新するように、ViewControllerのupdatePlayInfo()を修正。

class ViewController: UIViewController {

    /// 再生中の曲の情報を表示
    func updatePlayInfo() {
        if let item = g_musicPlayer.nowPlayingItem {
            titleLabel.text = item.title
            detailLabel.text = "\(item.artist) - \(item.albumTitle)"
        } else {
            titleLabel.text = "MusicPlayerTips"
            detailLabel.text = ""
        }

        // テーブルビューも更新
        playlistTable.reloadData()
    }

    ※関係ない部分は省略
}

実際に動かしてみるとこんな感じに。

f:id:see_ku:20150607102934p:plain

セルをタッチで曲を再生。曲の前後移動も普通に画面に反映されるようになってるはず。たぶん。

ソースコード

最終的なソースコードはこちら。

See_Ku / MusicPlayerTips — Bitbucket
https://bitbucket.org/See_Ku/musicplayertips

https://itunes.apple.com/jp/app/46-minute-shuffle/id991599315?mt=8&uo=4&at=10l8JW&ct=hatenablog