【Swift】音声ファイルを再生する

環境

Xcode 12.5

Swift 5.4


AVAudioPlayerを使用して音声ファイルを再生します

再生するファイルはプロジェクト内に入れているファイルを使用します

1.AVFoundationをimport

import AVFoundation

2.AVAudioPlayer

var player:AVAudioPlayer!

3.ファイルを取得してプレイヤーを作成

※音声ファイルは sample.aac

//ファイルパスの取得
guard let path = Bundle.main.path(forResource: "sample", ofType: "aac") else 
    print("file not found")
    return
}
//音声ファイルの読み込みと再生
do {
    player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
    player.delegate = self
    player.play()
}catch{
    print("Playback failed")
}

4.AVAudioPlayerDelegate

再生が終了した際に呼ばれるDelegateです。

再生終了後に何か処理をおこないたい場合に使用します

func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    print("finish!")    
}

ViewControllerの全文

import UIKit
import AVFoundation

class ViewController: UIViewController , AVAudioPlayerDelegate {
    
    var player:AVAudioPlayer!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.audioPlay()
        
    }
    
    func audioPlay(){
        //ファイルパスの取得
        guard let path = Bundle.main.path(forResource: "sample", ofType: "aac") else {
            print("file not found")
            return
        }
        
        //音声ファイルの読み込みと再生
        do {
            player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
            player.delegate = self
            player.play()
        }catch{
            print("Playback failed")
        }
    }
    
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        print("finish!")   
    }
}