LoginSignup
15
14

More than 5 years have passed since last update.

音楽再生する簡単な方法

Last updated at Posted at 2016-01-17

最近、AVAudioPlayerを使ってみたのでまとめておきます。
AVAudioPlayerは純粋にiphoneアプリで曲再生する方法として最も簡単に使える公式ライブラリです。
環境はswift2.1.1, xcode7です。
AVAudioPlayerを使った音楽再生をするためにやることは以下の3つです。

  1. 音楽ファイルの準備
  2. 再生準備
  3. 再生・停止

音楽ファイルの準備

MP3などの音楽ファイルを用意しましょう。
以下の様な感じにプロジェクト内に音楽ファイルを配置します。
スクリーンショット 2016-01-17 19.32.15.png

再生準備

曲を再生すつ前に、AVFoundationをimportした上で以下のプログラムを実行しておきましょう。
曲再生用の画面があるならば、画面のUIViewControllerのviewDidLoadとかで実行するのがいいかと思います。

do {
  // 音楽ファイルが"sample.mp3"の場合
  let filePath = NSBundle.mainBundle().pathForResource("sample", ofType: "mp3")
  let audioPath = NSURL(fileURLWithPath: filePath!)
  audioPlayer = try AVAudioPlayer(contentsOfURL: audioPath)
  audioPlayer.prepareToPlay()
} catch {
  print("Error")
}

再生・停止

再生準備の時に生成されたaudioPlayerを用いて曲の制御ができます。

audioPlayer.play() // 音楽の再生
audioPlayer.stop() // 音楽の停止
audioPlayer.playing // 再生しているか?
15
14
0

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
15
14