iOS - AVFoundation / 음악 재생

이한솔·2023년 8월 10일
0

iOS 앱개발 🍏

목록 보기
9/49

음악 재생 하는 법

1. 음원 파일을 프로젝트 폴더에 저장한다.

2. import AVFoudation

import AVFoundation


오디오 플레이에 사용하고 볼륨, 속도, 반복등을 제어할 수 있는 기능, 여러 사운드를 동시에 재생할 수 있는 기능을 제공한다.

3. audioPlayer 인스턴스 선언

class ViewController: UIViewController {
    
    var audioPlayer: AVAudioPlayer?
    
}

4. 음원파일을 찾아서 해당 파일을 audioPlayer를 실행하는 메소드 구현

 func playSound(_ soundName: String) {
            let url = Bundle.main.url(forResource: soundName, withExtension: "wav")
            player = try! AVAudioPlayer(contentsOf: url!)
            player.play()
            
        }       

 func playSound() {
        let url = Bundle.main.url(forResource: "alarm_sound", withExtension: "mp3")
        player = try! AVAudioPlayer(contentsOf: url!)
        player.play()
    }

5. 음원 재생을 원하는 곳에 함수 실행

@IBAction func keyPressed(_ sender: UIButton) {
   playSound(sender.currentTitle!)
   sender.layer.opacity = 0.5
        
   DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
      sender.layer.opacity = 1.0
}
 

 if self.secondsCount > totalTime {
    self.timer?.invalidate()
    self.titleLabel.text = "DONE!"
    playSound()
            
 }

0개의 댓글