6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

swiftで音声を再生する

Posted at

swiftを勉強し始めたのでメモ

やりたいこと

  • IOSでボタンを押したら音声が再生・停止される
  • 音量を調整できる

環境

  • Xcode: Version 10.1 (10B61)
  • mac: 10.14.1
  • swift: 4

方針

  • ストーリーボードで実施
  • AVFoundation(音声や画像、動画の作成や再生の細かい作業を行うためのAPIフレームワーク)を使用
  • ViewControllerに全部書くと冗長な気がしたので、extensionを用いて音声周りのメソッドを定義
  • Main.storybordと同じ階層にwater.mp3を置いてこれを再生・停止・音量調整する

実装


import UIKit
import AVFoundation

class ViewController: UIViewController {
    var audioPlayer: AVAudioPlayer!
    var soundFlag: Bool = true
    @IBOutlet weak var volume: UISlider!

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

    @IBAction func tapButton(_ sender: Any) {
        if soundFlag{
            playSound(name: "water", onSound: true)
            soundFlag = false
        } else {
            playSound(name: "water", onSound: false)
            soundFlag = true
        }
        
    }
    
    // volume調整
    @IBAction func changeVolume(_ sender: Any) {
        if audioPlayer != nil {
            audioPlayer.volume = volume.value
        }
    }
}

extension ViewController: AVAudioPlayerDelegate {
    func playSound(name: String, onSound: Bool) {
        guard let path = Bundle.main.path(forResource: name, ofType: "mp3") else {
            print("音源ファイルが見つかりません")
            return
        }
        
        do {
            
            // AVAudioPlayerのインスタンス化
            audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
            
            // AVAudioPlayerのデリゲートをセット
            audioPlayer.delegate = self
            
            if onSound{
                // 音声の再生
                audioPlayer.play()
            } else {
                audioPlayer.stop()
            }
        } catch {
        }
    }
}

ざっくり解説

  • playSoundは引数にString型のname, Bool肩のonSoundを指定して上げる
  • name: mp3ファイル名(例:water.mp3)
  • onSound: true → 再生 / false → 停止

おわりに

以上です。swiftすぐ動くからたのしいですなあ〜
不備・指摘などはコメントかツイッターでおねがいします🙏🏻

6
6
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
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?