← Back to Tutorials

10. Multimedia

Multimedia

AVAudioPlayer

Play audio files locally:

import AVFoundation

guard let url = Bundle.main.url(forResource: "music",
    withExtension: "mp3") else { return }

do {
    let player = try AVAudioPlayer(contentsOf: url)
    player.volume = 1.0
    player.numberOfLoops = -1 // Infinite loop
    player.play()
} catch {
    print("Audio playback error: \(error)")
}

AVPlayer

Play video and streaming content:

import AVKit

let videoURL = URL(string: "https://example.com/video.mp4")!
let player = AVPlayer(url: videoURL)
let controller = AVPlayerViewController()
controller.player = player

present(controller, animated: true) {
    player.play()
}

Camera & Photo Library

Capture photos and pick from library:

import PhotosUI

// PHPicker (modern, iOS 14+)
var config = PHPickerConfiguration()
config.selectionLimit = 5
config.filter = .images
let picker = PHPickerViewController(configuration: config)
picker.delegate = self
present(picker, animated: true)

// Delegate
func picker(_ picker: PHPickerViewController,
    didFinishPicking results: [PHPickerResult]) {
    dismiss(animated: true)
    // Process selected images
}

Core Image

Apply filters to images:

import CoreImage

let context = CIContext()
let image = CIImage(image: originalImage)!

let filter = CIFilter(name: "CISepiaTone")!
filter.setValue(image, forKey: kCIInputImageKey)
filter.setValue(0.8, forKey: kCIInputIntensityKey)

if let output = filter.outputImage,
   let cgImage = context.createCGImage(output, from: output.extent) {
    let filteredImage = UIImage(cgImage: cgImage)
}

Speech Recognition

Convert speech to text with SFSpeechRecognizer:

import Speech

let recognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))!
let request = SFSpeechURLRecognitionRequest(url: audioFileURL)

recognizer.recognitionTask(with: request) { result, error in
    if let result = result {
        print(result.bestTranscription.formattedString)
    }
}
Practice Task: Create a "Media Player" app with play/pause controls, a progress slider, and volume control. Use AVAudioPlayer for local audio files. Add a filter editor that applies sepia, blur, and vibrance filters to photos from the photo library. Implement speech-to-text on a recorded audio note.