LoginSignup
28
27

More than 5 years have passed since last update.

【Swift】バックグランドの音楽とアプリ内の効果音(AVfoundation)を同時に再生する

Posted at

備忘録です。

音楽を鳴らしながら利用できるアプリを作りたかったのですが、
アプリの中でAVfoundationで効果音を鳴らすと後ろで流している音楽が止まってしまいました。
それを解消するときのポイントです。

ポイント

・鳴らす効果音はcaf形式にすること
・appdelegate内でおまじないをすること

効果音はcaf

mp3形式の効果音を利用していましたが、caf形式に変換する必要があります。
cafへの変換はmacであればターミナルで

$ afconvert -f caff -d 0 "元ファイル.mp3" "新しいファイル.caf"

などで変換可能です。

AppDelegateでおまじない

AppDelegate.swift

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {        

        // バックグラウンドでの音の再生を許可
        let audioSession : AVAudioSession = AVAudioSession.sharedInstance()
        audioSession.setCategory(AVAudioSessionCategoryAmbient, error: nil)

        return true
    }

が自分の場合は必要でした。
デフォルトではAVFoundationは他音声と同時再生しない仕様になっているそうです。
バックグラウンドで音楽と共存できない!という方がいればお試しください

参考

http://www.ecoop.net/memo/archives/ios_play_sounds_and_background_music_simultaneously.html
https://developer.apple.com/jp/documentation/AudioSessionProgrammingGuide.pdf
https://sites.google.com/a/gclue.jp/swift-docs/ni-yinki100-ios/3-avfoundation/001-yin-yuanno-zai-sheng

28
27
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
28
27