일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- optional
- initalizer
- Swift
- Class
- instance
- Unicode
- 디자인패턴
- tuist
- Foundation
- 코딩테스트
- interpace
- String
- Protocol
- Git
- 이니셜라이저
- 스위프트
- Method
- type
- property
- struct
- Xcode
- Terminal
- enum
- init
- initializer
- url
- UIKit
- extension
- IOS
- delegate
Archives
- Today
- Total
아리의 iOS 탐구생활
[iOS] local에 있는 오디오파일 재생하는 방법 본문
반응형
AVAudioPlayer
Apple Developer Documentation
developer.apple.com
파일이나 메모리의 오디오 데이터를 재생하는 것들 담당하는 타입이다.
local에 있는 오디오 파일을 재생할 수 있다.
AVAudioPlayer가 할 수 있는 일은 다음과 같다.
- Play sounds of any duration
- Play sounds from files or memory buffers
- Loop sounds
- Play multiple sounds simultaneously, one sound per audio player, with precise synchronization
- Control relative playback level, stereo positioning, and playback rate for each sound you are playing
- Seek to a particular point in a sound file, which supports such application features as fast forward and rewind
- Obtain data you can use for playback-level metering
사용방법
import AVFoundation 해준다.
클래스 바깥에 다음과 같은 인스턴스를 만들어준다.
var player: AVAudioPlayer?
이후 로컬에 있는 파일을 재생하기 위한 경로를 아래와 같이 만들어 준다.
guard let url = Bundle.main.url(forResource: soundName, withExtension: "wav") else { return }
do-catch문을 이용하여 위에서 만들어 두었던 player 인스턴스를 마저 초기화 해준다.
do {
player = try AVAudioPlayer(contentsOf: url)
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
Full Code
import AVFoundation
func playSound(_ soundName: String) {
guard let url = Bundle.main.url(forResource: soundName, withExtension: "wav") else { return }
do {
player = try AVAudioPlayer(contentsOf: url)
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
Reference
iOS ) local에 있는 오디오파일 재생하기
안녕하세요 :) Zedd입니다. 네..............리젝이 벌써 4번째인가요..?네.....다른앱을 만들어야 하는지 ㅠㅠㅠ 열심히 만든건데.. 이것때문에 하루종일 메일함만 들여다보고 있네요 XD.... 이제 iOS글
zeddios.tistory.com
How to play a sound using Swift?
I would like to play a sound using Swift. My code worked in Swift 1.0 but now it doesn't work anymore in Swift 2 or newer. override func viewDidLoad() { super.viewDidLoad() let url:NSURL =
stackoverflow.com
반응형
'Swift > iOS' 카테고리의 다른 글
[iOS/Swift] Notification, NotificationCenter (0) | 2021.10.20 |
---|---|
[iOS] Timer를 간단히 사용해보기. (0) | 2021.09.30 |
[iOS] Bundle이 뭘까? (0) | 2021.09.28 |
[iOS/Xcode] Auto Layout에 대해 알아보자. (1) | 2021.09.27 |
[Swift/iOS] FileManager로 파일 생성(쓰기), 읽기, 삭제하기 (3) | 2021.08.27 |
Comments