Media makes it stupid simple to work with media capture & playback in Swift.
- Open your Swift project in Xcode.
- Go to
File
->Add Package Dependency
. - In the search bar, enter this URL.
- Choose the version you'd like to install.
- Click
Add Package
.
+ import Media
import SwiftUI
import Media
struct MyCameraView: View {
@State private var capturedImage: UIImage? = nil
var body: some View {
CameraViewReader { (cameraProxy: CameraViewProxy) in
CameraView(camera: .back, mirrored: false)
.safeAreaInset(edge: .bottom) {
captureButton(camera: cameraProxy) { image in
self.capturedImage = image
}
}
}
}
@ViewBuilder
private func captureButton(camera: CameraViewProxy, onCapture: @escaping (UIImage) -> Void) -> some View {
Button {
Task { @MainActor in
let image: UIImage = try! await camera.capturePhoto()
onCapture(image)
}
} label: {
Label {
Text("Capture Photo")
} icon: {
Image(systemName: .cameraFill)
}
.font(.title2)
.controlSize(.large)
.padding(.small)
}
.buttonStyle(.borderedProminent)
}
}
Play audio using AudioPlayer
.
import Media
struct MyAudioTask {
@MainActor
func playAudio(forFile fileURL: URL) {
Task {
// This line will suspend until the audio has finished playing!
try await AudioPlayer().play(.url(fileURL))
}
}
}
Record audio using AudioRecorder
.
import Media
class MyClass {
// ... the rest of your code
@MainActor
let recorder = AudioRecorder()
@MainActor
func startRecording() async {
do {
try await recorder.record()
} catch {
print(error)
}
}
@MainActor
func stopRecording() async {
do {
try await recorder.stop()
} catch {
print(error)
}
}
// ... the rest of your code
}
let wavFileURL: URL = try await MediaAssetLocation.url(myOriginalFileURL).convert(to: .wav)
Media is licensed under the MIT License.