Skip to content

Instantly share code, notes, and snippets.

@aheze
Last active July 30, 2020 15:42
Show Gist options
  • Save aheze/aa81df873f4ec0c8492e495eb4c7df7b to your computer and use it in GitHub Desktop.
Save aheze/aa81df873f4ec0c8492e495eb4c7df7b to your computer and use it in GitHub Desktop.

How to play custom audio on Swift Playgrounds for iPad, using SwiftUI.

import AVFoundation
import SwiftUI
import PlaygroundSupport

struct SwiftUIAudioPlayerView: View {
    
    /// the audio player that will play your audio file. Can't be a local variable.
    /// Must be a `@State` property because we need to modify it later
    @State var audioPlayer: AVAudioPlayer?
    
    var body: some View {
        Button(action: {
            self.playAudio() /// play audio when tapped
        }) {
            Text("Play Audio!") /// what the button looks like
        }
    }
    
    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 swiftuiAudioPlayerView = SwiftUIAudioPlayerView()
PlaygroundPage.current.setLiveView(swiftuiAudioPlayerView)

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.

Full article on Medium, UIKit version here.

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