【swift】BGMを別クラスに画面遷移後に止める
こんなことで2時間ほどハマったのでメモ。色々考える前にとりあえず調べればよかったよ!
音楽を鳴らす時は「AVFoundation」を使いますが、いろんな画面で同じ音楽を鳴らしたり止めたりしたいこともあるかと思います。複数画面で一つのBGMを使って、どこの画面でもそのBGMをストップさせることができる実装方法です。
まず「AppDelegate.swift」で音楽ファイルを定義。
class AppDelegate: UIResponder, UIApplicationDelegate { var audioPlayer:AVAudioPlayer! = AVAudioPlayer() var sound_data = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("bgm", ofType: "mp3")!) func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. audioPlayer = try? AVAudioPlayer(contentsOfURL:sound_data) audioPlayer.play() //アプリ起動から音楽スタート audioPlayer.numberOfLoops = -1 //音楽ループ
音楽を止めたいクラスで「AppDelegate」をインスタンス化して、「stop」を使用する。
再スタートさせる時は「stop」を「play」に変えるだけ。
import AVFoundation class GameViewController: UIViewController{ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate func onClickSoundOnButton(sender: UIButton){ appDelegate.audioPlayer.stop() }