
playSound 함수
swift
UNFOLDED func playSound(soundName: String) { let url = Bundle.main.url(forResource: soundName, withExtension: "wav") player = try! AVAudioPlayer(contentsOf: url!) player.play() }
swift
UNFOLDEDimport Foundation import AVFoundation var audioPlayer: AVAudioPlayer? func playSound(sound: String, type: String) { if let path = Bundle.main.path(forResource: sound, ofType: type) { do { audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path)) audioPlayer?.play() } catch { print("사운드 파일을 재생할 수 없음") } } }
사용 방법
1. AVFoundation
import
2. AVAudioPlayer
을 옵셔널 변수로 가져옴
3. playSound
함수 코드 구현
4. playSound
함수를 sender
의 currentTitle!
로 호출함
swift
UNFOLDEDimport UIKit import AVFoundation class ViewController: UIViewController { var player: AVAudioPlayer! override func viewDidLoad() { super.viewDidLoad() } @IBAction func keyPressed(_ sender: UIButton) { // sender의 currentTitle 재생 playSound(soundName: sender.currentTitle!) // 버튼 클릭시 투명도 설정 sender.alpha = 0.5 // 버튼 클릭 지연 DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { sender.alpha = 1.0 } } // PlaySound 함수 func playSound(soundName: String) { let url = Bundle.main.url(forResource: soundName, withExtension: "wav") player = try! AVAudioPlayer(contentsOf: url!) player.play() } }
Stack Overflow 의 다른 함수 예제
search : How to play a sound using Swift?
읽어주셔서 감사합니다🤟
잘못된 내용이 있으면 언제든 피드백 부탁드립니다.
'USEFUL CODE' 카테고리의 다른 글
UIKit: 화면 터치하여 키보드 내리는 방법 - textField (2) | 2021.08.13 |
---|---|
(CODE) SwiftUI 컬러 익스텐션 만들기 - 헥스코드활용 (0) | 2021.05.08 |
(CODE) 자동으로 두 줄로 문장을 나눠주는 메서드 (0) | 2021.03.31 |
(CODE) 베젤이 없는 기종과 있는 기기에 SafeArea 각각 적용법 (0) | 2021.03.25 |
(CODE) DateFormatter - 한국날짜 형식으로 (1) | 2021.03.23 |