궁금한 내용을 검색해보세요!
이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.
서근 개발노트
티스토리에 팔로잉
USEFUL CODE

Swift : 번들에 있는 sound 파일 재생 함수

서근
QUOTE THE DAY

“ 코드의 90%는 개발 시간의 90%를 설명해준다. 나머지 10%는 그 시간에 일어났던 다른 일의 90%를 설명해준다. ”

- Tom Cargill (톰 카길)
Written by SeogunSEOGUN

Swift : 번들에 있는 sound 파일 재생 함수

playSound 함수

swift
UNFOLDED
func playSound(soundName: String) {
let url = Bundle.main.url(forResource: soundName, withExtension: "wav")
player = try! AVAudioPlayer(contentsOf: url!)
player.play()
}
swift
UNFOLDED
import 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함수를 sendercurrentTitle!로 호출함

swift
UNFOLDED
import 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?

 

 

읽어주셔서 감사합니다🤟

 

 


잘못된 내용이 있으면 언제든 피드백 부탁드립니다.


서근


위처럼 이미지 와 함께 댓글을 작성할 수 있습니다.