0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【個人的備忘】SwiftUI, AVFoundationを使って音を付ける

Last updated at Posted at 2021-05-15

1.Assets.xcassetsに音源を登録する

2.サンプルコード

import AVFoundation

struct MySes {
    private let bgm = try! AVAudioPlayer(data: NSDataAsset(name: "bgm")!.data)
    private let se1 = try! AVAudioPlayer(data: NSDataAsset(name: "se1")!.data)
    
    init() {
        bgm.numberOfLoops = -1 //-1: 無限ループ, 0: ループなし(初期値)
        bgm.volume = 0.05
        se1.volume = 0.08
    }

    func playBgm() {
        bgm.play()
    }
    func pauseBgm() {
        bgm.pause()
    }
    func stopBgm() {
        bgm.stop()
    }

    func playSe1() {
        se1.currentTime = 0 //連続再生(連打など)に対応
                            //頭に空白があるときや途中から再生するときにも使える
        se1.play()
    }
}
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?