Skip to content

Instantly share code, notes, and snippets.

@aheze
Last active July 7, 2020 03:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aheze/3b6dccc67dd0d0b8b4106994c700acc1 to your computer and use it in GitHub Desktop.
Save aheze/3b6dccc67dd0d0b8b4106994c700acc1 to your computer and use it in GitHub Desktop.
How to play custom audio on Swift Playgrounds for iPad, using UIKit. Replace "slow-spring-board" with the name of your audio file.
import AVFoundation
import SwiftUI
import PlaygroundSupport
class UIKitAudioPlayerView: UIView {
/// the audio player that will play your audio file. Can't be a local variable.
var audioPlayer: AVAudioPlayer?
/// so we only make and connect the button once
var hasLoadedView = false
var audioButton = UIButton()
/// the view is guarenteed to be loaded at `layoutSubviews()`
override func layoutSubviews() {
super.layoutSubviews()
if !hasLoadedView {
hasLoadedView = true
audioButton.setTitle("Play Audio!", for: .normal)
audioButton.setTitleColor(UIColor.blue, for: .normal)
backgroundColor = .white
addSubview(audioButton) /// add the button to the view
audioButton.addTarget(self, action: #selector(playAudio), for: .touchUpInside)
}
/// positioning (center-align the button)
let middleXOfView = bounds.width / 2
let middleYOfView = bounds.height / 2
let buttonFrame = CGRect(x: middleXOfView - 60, y: middleYOfView - 20, width: 120, height: 40)
audioButton.frame = buttonFrame
}
@objc func playAudio() { /// function to play audio
/// the URL of the audio file.
/// forResource = name of the file.
/// withExtension = extension, usually "mp3"
if let audioURL = Bundle.main.url(forResource: "slow-spring-board", withExtension: "mp3") {
do {
try self.audioPlayer = AVAudioPlayer(contentsOf: audioURL) /// make the audio player
self.audioPlayer?.numberOfLoops = 0 /// Number of times to loop the audio
self.audioPlayer?.play() /// start playing
} catch {
print("Couldn't play audio. Error: \(error)")
}
} else {
print("No audio file found")
}
}
}
let uikitAudioPlayerView = UIKitAudioPlayerView()
PlaygroundPage.current.setLiveView(uikitAudioPlayerView)
@aheze
Copy link
Author

aheze commented Jul 7, 2020

Before any of the code, you need to first have an audio file saved in the built-in Files app. Then, you must import it into your Swift Playgrounds project:

  1. Press the "+" icon
  2. Tap the paper icon
  3. Tap Insert From…, then select your audio file

Then replace "slow-spring-board" with its name.

SwiftUI version

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment