LoginSignup
6

More than 5 years have passed since last update.

iOSで音を鳴らす

Posted at

やりたいこと

  • ボタンを押すと音を鳴らしたい。

参考

実装

2つのボタンを配置し、それぞれに異なった音をマッピング。

import UIKit
import AVFoundation

class ViewController: UIViewController {

    //共通で使うのでグローバルで宣言
    var audioPlayerInstance1 : AVAudioPlayer!
    var audioPlayerInstance2 : AVAudioPlayer!

    override func viewDidLoad() {
        super.viewDidLoad()

        //音の初期化
        makeSound()
    }

    //音の初期化
    func makeSound(){

        //ファイル設定

        //sound1
        let soundFilePath1 = Bundle.main.path(forResource: "decision-4", ofType: "mp3")!
        let sound1:URL = URL(fileURLWithPath: soundFilePath1)

        //sound2
        let soundFilePath2 = Bundle.main.path(forResource: "decision-1", ofType: "mp3")!
        let sound2:URL = URL(fileURLWithPath: soundFilePath2)


        //AVAudioPlayerのインスタンス作成
        do {
            audioPlayerInstance1 = try AVAudioPlayer(contentsOf: sound1, fileTypeHint:nil)
            audioPlayerInstance2 = try AVAudioPlayer(contentsOf: sound2, fileTypeHint:nil)

        } catch {

            print("AVAudioPlayerインスタンス作成失敗")

        }

        //バッファに保持
        audioPlayerInstance1.prepareToPlay()
        audioPlayerInstance2.prepareToPlay()

        print("Sound準備完了")
    }


    @IBAction func playSound(_ sender: Any) {

        //再生
        audioPlayerInstance1.play()

    }
    @IBAction func playSound2(_ sender: Any) {

        //再生
        audioPlayerInstance2.play()
    }
}

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