AVPlayerViewController using audio-only AVPlayer

只谈情不闲聊 提交于 2019-11-28 11:26:50

Do not use the AVPlayerViewController, as it is a full screen, black box, video player.

Instead, create your own view controller with, say, a toolbar and controls readily available in the OS (play, pause, stop, etc.) and hook them to your AVAudioPlayer. This is what the code of your very own view controller may look like:

Maintain an instance of the player

var audioPlayer:AVAudioPlayer!
@IBOutlet weak var playProgress: UIProgressView!

Example: Play

@IBAction func doPlayAction(_ sender: AnyObject) {
    do {
        try audioPlayer = AVAudioPlayer(contentsOf: audioRecorder.url)
        audioPlayer.play()
    } catch {}
}

Example: Stop

@IBAction func doStopAction(_ sender: AnyObject) {
    if let audioPlayer = self.audioPlayer {
        audioPlayer.stop()
    }
}

Example: Track progress

func playerProgress() {
    var progress = Float(0)
    if let audioPlayer = audioPlayer {
        progress = ((audioPlayer.duration > 0)
            ? Float(audioPlayer.currentTime/audioPlayer.duration)
            : 0)
    }
    playProgress.setProgress(progress, animated: true)
}

I have posted a recording and playback example using the methodology outlined in this answer.

► Find this solution on GitHub and additional details on Swift Recipes.

Why reinvent the wheel? Just use AVPlayerViewController's contentOverlayView property. Here you can set an album artwork image, or place any UIView between the QuickTime logo (where the video would be), and the controls.

Note that you must do this after the AVPlayerViewController has been presented, as its contentOverlayView property will be nil in prepareForSegue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!