3
2

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 1 year has passed since last update.

【Swift】AVPlayerの再生と一時停止を切り替える

Last updated at Posted at 2021-11-03

Swiftで導入したAVPlayerの再生と一時停止を切り替える方法。

今回はUIButtonで再生と一時停止を切り替える方法を書きます。

実装コード

モジュールを導入

import UIKit
import AVFoundation

変数・定数の定義

var videoPlayer: AVPlayer!

enum AVStatus {
    case playing
    case stoped
}
var av_status : AVStatus = .stoped

let switchbutton = UIButton()

AVPlayerの設定

guard let path = Bundle.main.path(forResource: "sample", ofType: "mp4") else {
    fatalError("動画が見つかりませんでした")
}
let fileURL = URL(fileURLWithPath: path)
let avAsset = AVURLAsset(url: fileURL)
let playerItem: AVPlayerItem = AVPlayerItem(asset: avAsset)

// AVPlayerの作成
videoPlayer = AVPlayer(playerItem: playerItem)

// AVPlayerを追加
let layer = AVPlayerLayer()
layer.videoGravity = AVLayerVideoGravity.resizeAspect
layer.player = videoPlayer
layer.frame = view.bounds
view.layer.addSublayer(layer)

再生・一時停止ボタンの設置

switchbutton.backgroundColor = UIColor.black
switchbutton.setTitle("再生する", for: UIControl.State.normal)
switchbutton.addTarget(self, action: #selector(onButtonTapped), for: UIControl.Event.touchUpInside)
view.addSubview(switchbutton)

*位置やサイズはお好みで設定してください。

ボタンタップの処理

@objc func onButtonTapped(){
    
    if av_status == .playing{
        switchbutton.setTitle("一時停止", for: UIControl.State.normal)
        videoPlayer.pause()
        av_status = .stoped
    }
    else{
        switchbutton.setTitle("再生中", for: UIControl.State.normal)
        videoPlayer.play()
        av_status = .playing
    }
}

参考

Swiftのお役立ち情報

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?