LoginSignup
0
1

More than 3 years have passed since last update.

AVFoundation 音再生

Posted at

音再生方法

まず AVFoundation をインポート

viewController.swift
import UIKit
import AVFoundation

class ViewController: UIViewController,AVAudioPlayerDelegate {

    var player :AVAudioPlayer!

まず、音ファイルをXcodeに追加。追加するのはここ!!
今回は 
umbrella と souziki が入っていますね。
スクリーンショット 2021-01-23 21.07.44.png

音声を呼び出す用の関数を定義!

viewController.swift

    public func prepareSound() {
        let soundFilePath = Bundle.main.path(forResource: "umbrella", ofType: "mp3")!
        let sound:URL = URL(fileURLWithPath: soundFilePath)
        do {
            player = try AVAudioPlayer(contentsOf: sound, fileTypeHint: nil)
            player?.delegate = self
        } catch {
            print("イエラー")
        }
        player?.delegate = self
        player?.prepareToPlay()
    }

viewDidLoad()に関数を記入

viewController.swift
    override func viewDidLoad() {
        super.viewDidLoad()

        prepareSound()

    }

あとは、ボタンなど、呼び出したいところで下記のオードを書けば

viewController.swift
    @IBAction func button(_ sender: Any) {

        if ((player?.isPlaying) != nil) {
            player?.stop()
            player?.currentTime = 0
        }
        player?.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