Unofficial Swift client for the Freesound API v2 with support for:
- API key auth (
Authorization: Token ...) - OAuth2 bearer auth (
Authorization: Bearer ...) - OAuth2 authorization-code + refresh token exchange
- Typed models for sound metadata + audio descriptor fields
Codablemodels you can cache or persist between launches withJSONEncoder/JSONDecoder- A
Sendableclient you can share across tasks and actors - Pagination helpers (
page(at:),nextPage,previousPage) - Preview downloads that work without OAuth (
downloadPreview) - Disk-backed asset cache for previews, images, and avatars (
FreesoundAssetCache) - Default-avatar monograms matching freesound.org (
AvatarMonogram) - Automatic rate-limit usage tracking against Freesound's throttle windows (
FreesoundUsageTracker)
- Swift 6 toolchain (Xcode 16+ on Apple platforms)
- macOS 15+, iOS 18+, tvOS 18+, watchOS 11+, visionOS 2+ (Linux and Android via Swift Package Manager)
In Package.swift:
.package(url: "https://github.com/codybrom/FreesoundKit.git", branch: "main")Then add "FreesoundKit" as a dependency to your target.
import FreesoundKit
let client = FreesoundClient(authentication: .apiKey("<YOUR_API_KEY>"))
let page = try await client.textSearch(query: "piano")
print(page.results.first?.name ?? "no results")
// Walk pages without rebuilding query parameters
if let next = try await client.nextPage(of: page) {
print("next page has \(next.results.count) results")
}
// Sort with the typed SoundSearchSort enum rather than raw strings
let popular = try await client.textSearch(
query: "piano", parameters: ["sort": SoundSearchSort.downloadsDescending.rawValue])
// Preview audio is public — no OAuth needed (request the "previews" field)
let sounds = try await client.textSearch(
query: "piano", parameters: ["fields": "id,name,previews"])
if let sound = sounds.results.first {
let mp3Data = try await client.downloadPreview(for: sound)
}import FreesoundKit
let client = FreesoundClient()
// 1. Send user to Freesound authorization page
let authURL = try client.oauthAuthorizationURL(
clientID: "<CLIENT_ID>",
responseState: "session-123"
)
// 2. After redirect, exchange the returned `code` for tokens
let token = try await client.exchangeAuthorizationCode(
clientID: "<CLIENT_ID>",
clientSecret: "<CLIENT_SECRET>",
code: "<AUTHORIZATION_CODE>"
)
// 3. Use OAuth token for protected endpoints
client.authentication = .oauthToken(token.accessToken)
let me = try await client.me()
print(me.username)
// 4. Refresh when needed
let refreshed = try await client.refreshAccessToken(
clientID: "<CLIENT_ID>",
clientSecret: "<CLIENT_SECRET>",
refreshToken: token.refreshToken
)textSearch,similaritySearchpage(at:),nextPage,previousPagefor any paged responsesound,soundAnalysis,similarSounds,soundComments,downloadOriginalSound,soundDownloadLink,downloadPreviewuploadSound,describeSound,editSound,pendingUploads,bookmarkSound,rateSound,commentSounduser,userSounds,userPackspack,packSounds,downloadPackme,myBookmarkCategories,myBookmarkCategorySoundsoauthAuthorizationURL,exchangeAuthorizationCode,refreshAccessToken,exchangePasswordGrant
All response models conform to Codable, so you can cache results in memory or persist them between launches with JSONEncoder/JSONDecoder:
// Persist a fetched sound, then restore it later without a network round-trip.
let data = try JSONEncoder().encode(sound)
let restored = try JSONDecoder().decode(Sound.self, from: data)Encoding mirrors the API's response shape — including the audio-descriptor fields that Sound and SoundAnalysis flatten to the top level — so a decode → encode → decode round-trip is lossless. (PagedResponse is encodable whenever its element type is.)
The value enums (SoundSearchSort, SoundLicense, SimilaritySpace, SoundPreviewFormat, SoundImageType, AvatarSize, APIUsageKind, OAuthScope) are Codable too, so your own types that store one — say a saved search that holds a sort — synthesize Codable without a @retroactive workaround. Each encodes as a single stable string (the String-raw enums as their exact API token, e.g. "downloads_desc").
Models carry only URLs for previews, waveforms/spectrograms, and avatars. To cache the bytes, use FreesoundAssetCache — a disk-backed actor that downloads on a miss, serves from disk on a hit, de-duplicates concurrent requests for the same URL, and evicts least-recently-used files to stay under a byte budget:
let cache = FreesoundAssetCache(
client: client,
directory: URL.cachesDirectory.appending(path: "freesound-assets"))
let waveform = try await cache.imageData(for: sound) // .waveformM by default
let preview = try await cache.previewData(for: sound) // .hqMP3 by default
let avatar = try await cache.avatarData(for: user.avatar!) // works for User and MeFetch any asset URL directly with cache.data(for: url) (or, without a cache, client.downloadAsset(at:) / the typed client.downloadImage(for:type:)). The cache owns its directory — removeAll() deletes it wholesale, so give it a dedicated folder.
Freesound also returns
*_bw_*image keys, but its source documents them as byte-identical duplicates of the standard waveform/spectrogram images, soSoundImageTypemodels only the four distinct images.
When a user has no avatar, Freesound renders a letter monogram over a palette color. AvatarMonogram reproduces that exact selection (matching bw_user_avatar + AVATAR_BG_COLORS in the server source), so your fallback matches the website — no network request, all platforms:
let monogram = user.monogram // also me.monogram, or AvatarMonogram(username:)
let letter = monogram.letter // "R"
if let rgb = monogram.backgroundColor { // nil only for an empty username
let (r, g, b) = rgb.fractions // 0...1, e.g. SwiftUI Color(red: r, green: g, blue: b)
}Freesound throttles APIv2 requests on rolling windows (per minute and per day), applying a looser limit to reads and a stricter one to write actions. Pass a FreesoundUsageTracker to the client and it records every APIv2 request automatically — classified as a read or a write, and excluding traffic that isn't throttled (OAuth token exchanges and CDN asset downloads):
let tracker = FreesoundUsageTracker(limits: .level1) // default for new API keys
let client = FreesoundClient(authentication: .apiKey("…"), usageTracker: tracker)
_ = try await client.textSearch(query: "rain")
let usage = tracker.snapshot()
print("\(usage.standard.remainingThisMinute) reads left this minute")
print("\(usage.standard.remainingToday)/\(usage.standard.perDay) reads left today")Because the client tracks at the single point every request flows through, the count includes pagination and downloads — no need to instrument call sites. It's an estimate of this client's own traffic: Freesound throttles on the account that owns the credential, so any other app of yours spend the same budget without being tracked by this client. Persist it across launches by saving tracker.events(.standard) / .write and restoring them via init. Limits come from Freesound's published per-level throttle tables — use .level1 (default), .level2, or .level3 to match your key.
The two limits aren't two budgets. The server keeps a single request history per account and holds it against whichever limit the endpoint you called carries. Reads and writes spend the same counter, so 40 searches in a minute will throttle the next write even if you've made none. Both buckets in a snapshot will report the same usage and differ only in the limit; tracker.count(.standard, within: 60) gives the per-kind breakdown when you want it.
For SwiftUI, wrap the tracker in the optional @MainActor @Observable FreesoundUsageMonitor. It re-snapshots on a timer (the rolling windows decay with time, so a tick is needed even when idle) and republishes only when the snapshot changes, so you can bind snapshot directly:
@State private var usage = FreesoundUsageMonitor(tracker) // refreshes every 5s by default
// in a view body:
Text("\(usage.snapshot.standard.remainingToday) reads left today")All client methods throw FreesoundError, a typed enum:
do {
let page = try await client.textSearch(query: "thunder")
} catch let error as FreesoundError {
switch error {
case .apiError(let statusCode, let detail):
print("API error \(statusCode): \(detail)")
case .rateLimited(let retryAfter, let detail):
print("Throttled (\(detail)); retry after \(retryAfter ?? 60)s")
case .oauthRequired:
print("This endpoint needs an OAuth token")
default:
print(error.localizedDescription)
}
}You can verify the package without creating another project:
swift run freesound-tester helpExamples:
# API key smoke test
FREESOUND_API_KEY=... swift run freesound-tester search --query "piano"
# Build OAuth URL and open it in browser
FREESOUND_CLIENT_ID=... swift run freesound-tester oauth-url --state test
# Exchange returned code for tokens
FREESOUND_CLIENT_ID=... FREESOUND_CLIENT_SECRET=... \
swift run freesound-tester oauth-exchange --code "<CODE>"
# Test protected endpoint
FREESOUND_ACCESS_TOKEN=... swift run freesound-tester me
# Refresh token
FREESOUND_CLIENT_ID=... FREESOUND_CLIENT_SECRET=... FREESOUND_REFRESH_TOKEN=... \
swift run freesound-tester oauth-refreshThis library is an unofficial wrapper. Your use of the Freesound API is governed by Freesound's Terms of Use. A few obligations that affect apps built with this library:
- Non-commercial by default. The API is free for non-commercial use only; commercial use requires a separate licensing agreement with Freesound.
- Attribution. You must credit Freesound and the individual sound authors, and respect each sound's license (visible via
Sound.license). Surface this wherever you play or display sounds. - One key per app. Don't register multiple API keys to work around limits.
Freesound throttles requests (overview):
| Operation | Per minute | Per day |
|---|---|---|
| Standard (search, fetch) | 60 | 2,000 |
| Write (original-quality download, upload, describe, edit, comment, rate, bookmark) | 30 | 500 |
As of September 14, 2026, original-quality sound and pack downloads are measured against the stricter write limit, not the standard one, even though they are GET requests. Download-heavy apps should expect lower per-minute and per-day ceilings. FreesoundUsageTracker classifies them accordingly.
Both rows count the same requests: the server keeps one history per account and compares it against the limit for whichever endpoint you called. A minute of reads eats into the write allowance and vice versa.
When a limit is exceeded the API responds 429, surfaced here as FreesoundError.rateLimited(retryAfter:detail:) — retryAfter carries the server's Retry-After hint in seconds when present, and detail says which limit was hit. Contact Freesound if you need higher limits.
To honor Retry-After automatically, wrap an idempotent call in withRateLimitRetry:
let page = try await client.withRateLimitRetry {
try await client.textSearch(query: "rain")
}