LoginSignup
0
1

More than 3 years have passed since last update.

7日目トリガーをボタンにしたピンクの音色再生その2

Last updated at Posted at 2021-02-26

7日目のアプリ

トリガーをボタンにした音声再生その2

画面キャプチャ

以下の流れで作りました。

  1. storyboadに複数ボタンを配置。
  2. 上記要素をViewController.swiftへoptionドラッグして紐付ける
  3. 紐付けができたら、ViewController.swiftでコードを書く

できたこと

  • 複数のボタンをトリガーにした音声ファイルの再生方法がわかった。
  • ボタンのcurrentTitleを取得して、音声ファイル名に紐付けて再生する方法がわかった。 ##書いたコードを共有します!
import UIKit
import AVFoundation

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    var player: AVAudioPlayer!

    func playSound(pressedKey: String) {

        let url = Bundle.main.url(forResource: pressedKey, withExtension: "wav")
        player = try! AVAudioPlayer(contentsOf: url!)
        player.play()
    }

    @IBAction func keyPressed(_ sender: UIButton) {

        playSound(pressedKey: sender.currentTitle!)


    }


}

感想

func()のかっこ()の中は、変数的なものと、その変数的なものがIntなのかStringなのかみたいな型を記載すること。
例: func playSound(pressedKey: String)
で、
関数を呼び出すときに、()の中に、引数を入れること
例: playSound(pressedKey: sender.currentTitle!)
ふむむ。

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