LoginSignup
6
6

More than 5 years have passed since last update.

AVAudioPlayerで音楽を再生する

Last updated at Posted at 2016-01-28

はじめに

製作したゲームの中で音楽を流したかったのですが、調べに調べて「どうやらAVAudioPlayerというものを使うらしい」というところまでは辿り着いたのですが、調べたページのコードを参考にしても、どうもうまくいかず、ずっと匙を投げたり放置したりしていたのですが、やっとまともに音楽が再生できました。

理解はできてませんがとりあえずできた方法を忘れないように書いておきます。

環境

swift 2
Xcode 7.2

手順

1.AVFounditionフレームワークを追加する。
2.Supporting Filesに音楽ファイルをドラッグ&ドロップする。
3.ViewControllerにimport AVFounditionを書く。
4.ViewControllerクラスにAVAudioPlayerDelegateを継承させる。
5.ViewControllerクラスの中でAudioPlayerを宣言する。

var audioPlayer = AVAudioPlayer()

6.再生するクラス(TitleSceneとします)にもimport AVFounditionを書く。
7.TitleSceneクラスの中でViewControllerをインスタンス化する。

let gameVC = GameViewController()

8.再生したい場所に以下のコードを書く。

let titleSound = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource("scene1", ofType: "mp3")!)

do {
    gameVC.audioPlayer = try AVAudioPlayer(contentsOfURL: titleSound, fileTypeHint: nil)
} catch {
    print("なんかダメみたい")
}

gameVC.audioPlayer.prepareToPlay()
gameVC.audioPlayer.play()
gameVC.audioPlayer.numberOfLoops = -1

※音楽ファイル名:scene1.mp3

9.止めたい場所に以下のコードを書く。

gameVC.audioPlayer.stop()

8のコードtry catchの部分は最初以下のように書いてたんですがどうしてもエラーが出てしまってつまづいていました。何がいけなかったのか、わかる方がいたら是非教えてください。。
スクリーンショット 2016-01-28 17.18.19.png

参考サイト

【Swift】音を鳴らす - とりあえず何でも書く

iOS8 音を鳴らす

[iPhone] AVAudioplayer 音楽の再生 (Swift)

【Swift】AVFoundationでサウンドを再生する

いつも本当に助かってます。ありがとうございます。

6
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6