Just starting out with AVKit, and I\'m trying to play some audio. It would be nice to use the new AVPlayerViewController detailed in Mastering Modern Media Playback so that
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.