ios - How to play a sound using Swift? -
i play sound using swift.
my code worked in swift 1.0 doesn't work anymore in swift 2 or newer.
override func viewdidload() { super.viewdidload() let url:nsurl = nsbundle.mainbundle().urlforresource("soundname", withextension: "mp3")! { player = try avaudioplayer(contentsofurl: url, filetypehint: nil) } catch _{ return } bgmusic.numberofloops = 1 bgmusic.preparetoplay() if (data.backgroundmenuplayed == 0){ player.play() data.backgroundmenuplayed = 1 } }
most preferably might want use avfoundation. provides essentials working audiovisual media.
update: compatible swift 2, swift 3 , swift 4 suggested of in comments.
swift 2.3
import avfoundation var player: avaudioplayer? func playsound() { let url = nsbundle.mainbundle().urlforresource("soundname", withextension: "mp3")! { player = try avaudioplayer(contentsofurl: url) guard let player = player else { return } player.preparetoplay() player.play() } catch let error nserror { print(error.description) } }
swift 3
import avfoundation var player: avaudioplayer? func playsound() { guard let url = bundle.main.url(forresource: "soundname", withextension: "mp3") else { return } { try avaudiosession.sharedinstance().setcategory(avaudiosessioncategoryplayback) try avaudiosession.sharedinstance().setactive(true) player = try avaudioplayer(contentsof: url) guard let player = player else { return } player.play() } catch let error { print(error.localizeddescription) } }
swift 4 (ios 11 compatible)
import avfoundation var player: avaudioplayer? func playsound() { guard let url = bundle.main.url(forresource: "soundname", withextension: "mp3") else { return } { try avaudiosession.sharedinstance().setcategory(avaudiosessioncategoryplayback) try avaudiosession.sharedinstance().setactive(true) /* following line required player work on ios 11. change file type accordingly*/ player = try avaudioplayer(contentsof: url, filetypehint: avfiletype.mp3.rawvalue) /* ios 10 , earlier require following line: player = try avaudioplayer(contentsof: url, filetypehint: avfiletypempeglayer3) */ guard let player = player else { return } player.play() } catch let error { print(error.localizeddescription) } }
make sure change name of tune extension. the file needs imported (
project build phases
>copy bundle resources
). might want place inassets.xcassets
greater convenience.
for short sound files might want go non-compressed audio formats such .wav
since have best quality , low cpu impact. higher disk-space consumption should not big deal short sound files. longer files are, might want go compressed format such .mp3
etc. pp. check compatible audio formats of coreaudio
.
fun-fact: there neat little libraries make playing sounds easier. :)
example: swiftysound
Comments
Post a Comment