LoginSignup
0
3

More than 3 years have passed since last update.

【備忘録】Swift4.0以降で音を鳴らす

Posted at

音を鳴らしたいだけ

 ある教材でアプリ開発を学んでいたら、音を鳴らすところがうまくいかない。そりゃそうだ。その教材、Swift3.0なんだもの。まぁ、私が過去に書いた4.2を引っ張ってきてぶち込んだから問題なくできたけど。。。こんな感じで今後も「音を鳴らすだけ」のためにわざわざ過去のProject開いて確認するのめんどいな、、と思ってここに書いておく。

こんな感じ

ViewController.swift
import UIKit
import AVFoundation

class ViewController: UIViewController {

    var audioPlayer: AVAudioPlayer!

    @IBAction func btn(_ sender: UIButton) {

        playSound(name: "yourFileName")

    }

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

extension ViewController: AVAudioPlayerDelegate{

    func playSound(name: String){

        guard let path = Bundle.main.path(forResource: name, ofType: "mp3") else {
            print("I cannot find any music file...")
            return
        }
        do{
            audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))

            audioPlayer.delegate = self

            audioPlayer.play()
        } catch {
        }
    }
}

yourFileName.mp3っていうファイルを入れておくと、ボタンを押した時にそれが流れる。

0
3
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
3