본문 바로가기
아이폰 개발/Swift

swift AVAudioPlayer 로 음악앱 만들기

by 인생여희 2021. 10. 10.

swift AVAudioPlayer 로 음악앱 만들기

 

 

 

 

 

 

스토리 보드 구성은 아래와 같이 음악 리스트를 보여줄 뷰 컨트롤러 하나.

음악을 재생시킬 뷰컨트롤러 하나.

총 두개를 만들고 네비게이션 컨트롤러로 만들어 준다.

 

 

 

ViewController.swift - 음악 리스트 보여주기

import UIKit

class ViewController: UIViewController , UITableViewDelegate, UITableViewDataSource{

    @IBOutlet var table:UITableView!
    var songs = [Song]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configureSongs()
        self.table.delegate = self
        self.table.dataSource = self
        
        
    }

    
    func configureSongs(){
        
        for i in 0 ..< 11 {
            
            let song = Song(name: "01-0\(i).mp3",
                            albumName: "어원 덕분에 영어공부가 쉬워졌습니다",
                            artistName: "artistName1",
                            imageName: "album",
                            trackName: "01-0\(i)")
            
            songs.append(song)
        }
        
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return songs.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        let song = songs[indexPath.row]
        cell.textLabel?.text = song.trackName
        cell.detailTextLabel?.text = song.albumName
        cell.accessoryType = .disclosureIndicator
        cell.imageView?.image = UIImage(named: song.imageName)
        cell.textLabel?.font = UIFont(name: "Helvetica-Bold", size: 18)
        cell.detailTextLabel?.font = UIFont(name: "Helvetica", size: 17)

        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let position = indexPath.row
        guard let vc = storyboard?.instantiateViewController(identifier: "player") as? PlayerVC else {
            return
        }
        
        vc.songs = songs
        vc.position = position

        present(vc, animated: true, completion: nil)
    }

    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
}

//MARK: 모델
struct Song {
    let name:String
    let albumName : String
    let artistName:String
    let imageName:String
    let trackName:String
}

 

PlayerVC.swift - 음악 재생기능

 

import AVFoundation
import UIKit

class PlayerVC: UIViewController {

    public var position:Int = 0
    public var songs:[Song] = []
    
    @IBOutlet var holder:UIView!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var subLabel: UILabel!
    
    @IBOutlet weak var playPauseBtn: UIButton!
    @IBOutlet weak var slider: UISlider!
    var player: AVAudioPlayer?

    // user interface elements
    
    override func viewDidLoad() {
        super.viewDidLoad()
        print("viewDidLoad")

        configure()
        
    }
    
    
//    override func viewDidLayoutSubviews() {
//        super.viewDidLayoutSubviews()
//        print("viewDidLayoutSubviews")
//        print("holder.subviews.count : \(holder.subviews.count)")
//        if holder.subviews.count == 0 {
//            configure()
//        }
//    }


    func configure(){
        // set up player
        let song = songs[position]
        
        let urlString = Bundle.main.path(forResource: song.trackName, ofType: "mp3")
        
        do {
            try AVAudioSession.sharedInstance().setMode(.default)
            try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
            try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
            
            guard let urlString = urlString else {
                print("urlString is nil")
                return
            }
            
            player = try AVAudioPlayer(contentsOf: URL(string: urlString)!)
            
            guard let player = player else {
                print("player is nil")
                return
            }
            
            playPauseBtn.setImage(UIImage.init(systemName: "pause"), for: .normal)
            player.volume = 0.5
            player.numberOfLoops = 0
            player.play()
            
        } catch  {
            print("오류발생..")
        }
        

        // set up user interface element
        imageView.image = UIImage(named: song.imageName)
        titleLabel.text = song.albumName
        subLabel.text = song.trackName
        
        //album cover
    }

    
    // 앞으로
    @IBAction func clickForwardBtn(_ sender: UIButton) {
        print("clickForwardBtn..")
        if position < (songs.count - 1) {
            position = position + 1
            player?.stop()
        }
        configure()

    }
    
    // 플레이
    @IBAction func clickPlayPauseBtn(_ sender: UIButton) {
        print("clickPlayPauseBtn..")
        
        if player?.isPlaying == true {
            player?.pause()
            playPauseBtn.setImage(UIImage.init(systemName: "play"), for: .normal)
            
        }else {
            player?.play()
            playPauseBtn.setImage(UIImage.init(systemName: "pause"), for: .normal)
        }

    }
    
    //뒤로
    @IBAction func clickBackBtn(_ sender: UIButton) {
        print("clickBackBtn..")
        if position > 0 {
            position -= 1
            player?.stop()
        }
        configure()
    }
    
    
    
    @IBAction func changeSlider(_ sender: UISlider) {
        
        print("changeSlider click : \(sender.value)")
        
        player?.volume = sender.value
    }
    
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if let player = player {
            player.stop()
        }
    }
    
}

 

 

소스코드