SPB Git

Repository Public

TestSupport.swift 4.5 KB 121 lines swift

1// ORIX DJ2// File: Packages/ORIXDJCore/Tests/ORIXLibraryTests/TestSupport.swift3// Description: Test helpers: temporary directories, synthetic audio files written with AVAudioFile, sample tracks.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai78import AVFoundation9import Foundation10@testable import ORIXLibrary1112/// A temporary directory removed when the value is deallocated.13final class TempDirectory {14    let url: URL1516    init(_ label: String = "orixlib") {17        let base = FileManager.default.temporaryDirectory.resolvingSymlinksInPath()18        url = base.appendingPathComponent("\(label)-\(UUID().uuidString)", isDirectory: true)19        try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)20    }2122    deinit { try? FileManager.default.removeItem(at: url) }2324    func file(_ name: String) -> URL { url.appendingPathComponent(name) }2526    func directory(_ name: String) -> URL {27        let directory = url.appendingPathComponent(name, isDirectory: true)28        try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)29        return directory30    }31}3233enum AudioFixture: String, CaseIterable {34    case wav, aiff, caf, m4aAAC, m4aALAC, flac, aacADTS3536    var fileExtension: String {37        switch self {38        case .wav: return "wav"39        case .aiff: return "aiff"40        case .caf: return "caf"41        case .m4aAAC, .m4aALAC: return "m4a"42        case .flac: return "flac"43        case .aacADTS: return "aac"44        }45    }4647    var settings: [String: Any] {48        var settings: [String: Any] = [AVSampleRateKey: 44_100.0, AVNumberOfChannelsKey: 2]49        switch self {50        case .wav, .caf:51            settings[AVFormatIDKey] = kAudioFormatLinearPCM52            settings[AVLinearPCMBitDepthKey] = 1653            settings[AVLinearPCMIsFloatKey] = false54            settings[AVLinearPCMIsBigEndianKey] = false55        case .aiff:56            settings[AVFormatIDKey] = kAudioFormatLinearPCM57            settings[AVLinearPCMBitDepthKey] = 1658            settings[AVLinearPCMIsFloatKey] = false59            settings[AVLinearPCMIsBigEndianKey] = true60        case .m4aAAC, .aacADTS:61            settings[AVFormatIDKey] = kAudioFormatMPEG4AAC62        case .m4aALAC:63            settings[AVFormatIDKey] = kAudioFormatAppleLossless64            settings[AVEncoderBitDepthHintKey] = 1665        case .flac:66            settings[AVFormatIDKey] = kAudioFormatFLAC67        }68        return settings69    }7071    /// Writes a 440 Hz sine of `seconds` to `url` with AVAudioFile. Throws when this macOS has no encoder/writer.72    func write(to url: URL, seconds: Double = 0.5) throws {73        let file = try AVAudioFile(forWriting: url, settings: settings)74        let format = file.processingFormat75        let frames = AVAudioFrameCount(seconds * format.sampleRate)76        guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frames) else {77            throw LibraryError.io("cannot allocate a PCM buffer")78        }79        buffer.frameLength = frames80        if let channels = buffer.floatChannelData {81            for channel in 0..<Int(format.channelCount) {82                for frame in 0..<Int(frames) {83                    channels[channel][frame] = Float(sin(2 * Double.pi * 440 * Double(frame) / format.sampleRate) * 0.25)84                }85            }86        }87        try file.write(from: buffer)88        file.close()89    }90}9192/// A silent MPEG-1 Layer III stream built by hand (no MP3 encoder ships with macOS): `frames` frames of93/// 128 kbit/s, 44.1 kHz, stereo, with zeroed side information and main data.94func writeSilentMP3(to url: URL, frames: Int = 60) throws {95    var data = Data()96    let frameLength = 417 // 144 * 128000 / 44100, no padding97    for _ in 0..<frames {98        var frame = Data(count: frameLength)99        frame[0] = 0xFF; frame[1] = 0xFB; frame[2] = 0x90; frame[3] = 0x64100        data.append(frame)101    }102    try data.write(to: url)103}104105func sampleTrack(_ name: String, artist: String = "Artist", album: String = "", genre: String = "",106                 bpm: Double? = nil, path: String? = nil) -> Track {107    Track(path: path ?? "/music/\(name).wav", title: name, artist: artist, album: album, genre: genre,108          duration: 200, sampleRate: 44_100, channels: 2, bitRate: 1_411_200, format: "wav", fileSize: 1_000, bpm: bpm)109}110111func expectLibraryError(_ expected: (LibraryError) -> Bool, _ body: () throws -> Void) -> Bool {112    do {113        try body()114        return false115    } catch let error as LibraryError {116        return expected(error)117    } catch {118        return false119    }120}121
Files main
Menu

Theme