39
33

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

概要

swift4で AVAudioPlayer を使ってサウンドを再生する

環境

macOS Sierra 10.12.6
Xcode 9.2
swift4

コード

AVFoundation のインポート

ViewController.swift
import AVFoundation

ViewControllerAVAudioPlayer のインスタンスを宣言

ViewController.swift
class ViewController: UIViewController {
    
    var audioPlayer: AVAudioPlayer!
    
    // 省略
}

ViewControllerAVAudioPlayerDelegate を継承させて拡張

ViewCountrollerクラス の下に、以下のコードを追記する。

ViewController.swift
extension ViewController: AVAudioPlayerDelegate {
    func playSound(name: String) {
        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
            
            // 音声の再生
            audioPlayer.play()
        } catch {
        }
    }
}

再生させたいタイミングでメソッドを呼ぶ

音源ファイルがSOUND_NAME.mp3だった場合

playSound(name: "SOUND_NAME")

以上のコードで音声ファイルが再生できます。

画面load時にすぐに再生する場合のViewController全体コード

ViewController.swift


import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    var audioPlayer: AVAudioPlayer!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // mp3音声(SOUND.mp3)の再生
        playSound(name: "SOUND_NAME")
        
    }
}

extension ViewController: AVAudioPlayerDelegate {
    func playSound(name: String) {
        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
            
            // 音声の再生
            audioPlayer.play()
        } catch {
        }
    }
}
39
33
1

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
39
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?