Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

音を鳴らしたいだけ

 ある教材でアプリ開発を学んでいたら、音を鳴らすところがうまくいかない。そりゃそうだ。その教材、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っていうファイルを入れておくと、ボタンを押した時にそれが流れる。

LilyMameoka
センスをメイキングする
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away