iOS/swift

swift5 - sound play with simple code

돌맹이시터 2021. 6. 15. 21:38

 

 

 

Simple code without error handling to play audio from your local path

 

 

import AVFoundation

var audio:AVPlayer!

func stopAlarm() {
    // To pause or stop audio in swift 5 audio.stop() isn't working
    audio.pause()
}

func playAlarm() {
    // need to declare local path as url
    let url = Bundle.main.url(forResource: "Alarm", withExtension: "mp3")
    // now use declared path 'url' to initialize the player
    audio = AVPlayer.init(url: url!)
    // after initialization play audio its just like click on play button
    audio.play()
}

 

 

 

 

 

'iOS > swift' 카테고리의 다른 글

MVC Design pattern  (0) 2021.06.28
Swift - structure (구조체)  (0) 2021.06.23
Swift - nil & Optional (물음표, 느낌표)  (0) 2021.06.12
Swift - Dictionary  (0) 2021.06.12
Swift 조건문 : If - Else & Switch  (0) 2021.06.11