ios - Audio not playing in simulator -
i have 3 buttons , i'm trying sound play each button.
the sounds don't play on simulator wondering going wrong in code.
import uikit import avfoundation class viewcontroller: uiviewcontroller { override func viewdidload() { super.viewdidload() } @ibaction func mmm_sound(sender: uibutton) { playsound("mmm") } @ibaction func aww_sound(sender: uibutton) { playsound("aww") } @ibaction func maniacal_sound(sender: uibutton) { playsound("hah") } //sound function func playsound(soundname: string) { let sound = nsurl(fileurlwithpath:nsbundle.mainbundle().pathforresource(soundname, oftype: "wav")!) do{ let audioplayer = try avaudioplayer(contentsofurl:sound) audioplayer.preparetoplay() audioplayer.play() }catch { print("error getting audio file") } } }
you should make avaudioplayer global variable local variable of 'avaudioplayer' deallocate before plays, code can
//at top var audioplayer = avaudioplayer() func playsound(soundname: string) { let sound = nsurl(fileurlwithpath:nsbundle.mainbundle().pathforresource(soundname, oftype:"wav")!) do{ audioplayer = try avaudioplayer(contentsofurl:sound) audioplayer.preparetoplay() audioplayer.play() }catch { print("error getting audio file") } }
Comments
Post a Comment