Skip to content

Instantly share code, notes, and snippets.

@aheze
Last active June 14, 2020 04:04
Show Gist options
  • Select an option

  • Save aheze/54677aedddd15cc6221c3be3ccc21f04 to your computer and use it in GitHub Desktop.

Select an option

Save aheze/54677aedddd15cc6221c3be3ccc21f04 to your computer and use it in GitHub Desktop.
import AVFoundation
import SwiftUI
import PlaygroundSupport
struct SwiftUIAudioPlayerView: View {
/// the player that will play the audio. It can't be a local variable.
/// Must have the `@State` attribute, because we need modify it later on
@State var audioPlayer: AVAudioPlayer?
/// the path for the audio. 'forResource' is the name of the file. 'withExtension' is the file format.
let audioURL = Bundle.main.url(forResource: "intro", withExtension: "mp3")
var body: some View {
Button(action: {
self.playAudio() /// play audio when pressed
}) {
Text("Play Audio!") /// what the button looks like
}
}
/// function to play the audio
func playAudio() {
/// `audioURL` is an optional, so we need to unwrap it
if let musicPath = audioURL {
/// making an AVAudioPlayer can throw an error, so we wrap it in a do-catch block
do {
try self.audioPlayer = AVAudioPlayer(contentsOf: musicPath)
self.audioPlayer?.numberOfLoops = -1 /// infinite loop
self.audioPlayer?.play()
} catch {
print("Couldn't play audio. Error: \(error)")
}
} else {
print("No audio file found")
}
}
}
let audioPlayerView = SwiftUIAudioPlayerView()
PlaygroundPage.current.setLiveView(audioPlayerView)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment