audio - Setup AVAudioPlayer with swift 1.2? -
when tried setup avaudioplayer last time, used code:
func setupaudioplayerwithfile(file:nsstring, type:nsstring) -> avaudioplayer { var path = nsbundle.mainbundle().pathforresource(file, oftype:type) var url = nsurl.fileurlwithpath(path!) var error: nserror? var audioplayer:avaudioplayer? audioplayer = avaudioplayer(contentsofurl: url, error: &error) return audioplayer! } var buttonbeep = avaudioplayer() buttonbeep = self.setupaudioplayerwithfile("buttonpush", type:"m4a")
and worked perfectly. swift 1.2 seems can't that.
i tried code:
var button : avaudioplayer? in didmovetoview: if let button = self.setupaudioplayerwithfile("button", type:"m4a") { self.button = button } func setupaudioplayerwithfile(file:nsstring, type:nsstring) -> avaudioplayer? { let path = nsbundle.mainbundle().pathforresource(file string, oftype: type string) let url = nsurl.fileurlwithpath(path!) var error: nserror? var audioplayer:avaudioplayer? audioplayer = avaudioplayer(contentsofurl: url, error: &error) return audioplayer }
it gives me error on let url line - exc_bad_instruction. put audio file in supporting files inside project. doing wrong?
update: mistake. if have same problem — make sure adding sounds target of app, not in project
try code:
var backgroundmusicplayer: avaudioplayer! func playbackgroundmusic(filename: string) { let url = nsbundle.mainbundle().urlforresource(filename, withextension: nil) if (url == nil) { println("could not find file: \(filename)") return } var error: nserror? = nil backgroundmusicplayer = avaudioplayer(contentsofurl: url, error: &error) if backgroundmusicplayer == nil { println("could not create audio player: \(error!)") return } backgroundmusicplayer.numberofloops = -1 backgroundmusicplayer.preparetoplay() backgroundmusicplayer.play() }
use way:
playbackgroundmusic("button.m4a")
hope helps.
it working fine 1.2 , didn't test right because have updated xcode , suggest use latest version of xcode have swift version 2.0.
Comments
Post a Comment