• Stars
    star
    308
  • Rank 135,712 (Top 3 %)
  • Language
    Swift
  • License
    MIT License
  • Created about 3 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A small library that makes it easier to play audio with SwiftUI.

Sitrep logo

Twitter: @twostraws

Subsonic is a small library that makes it easier to play audio with SwiftUI, allowing you to work both imperatively ("play this sound now") and declaratively ("play this sound when some state becomes true").

Subsonic works on iOS 14+, macOS 11+, tvOS 14+, and watchOS 7+.

Why "subsonic"? Because it's so small it's almost imperceptible ✨

Installation

To use Subsonic in a SwiftPM project, add the following line to the dependencies in your Package.swift file:

.package(url: "https://github.com/twostraws/Subsonic", from: "0.2.0"),

You should then add import Subsonic to your Swift files as needed.

Playing sounds

There are four ways to use Subsonic, depending on how much control you want.

Option 1: Just play a sound

If you just want to play an audio file from your bundle, call play(sound:) from inside any view:

Button("Play Sound") {
    play(sound: "example.mp3")
}

That will locate example.mp3 in your main bundle, then play it immediately. If you want to load the file from a different bundle, see below.

Option 2: Play a sound, but have control over it

If you want to play a sound while having precise control over its existence, you can create an @StateObject property containing a SubsonicPlayer object, like this:

struct ContentView: View {
    @StateObject private var sound = SubsonicPlayer(sound: "example.mp3")

    var body: some View {
        VStack {
            Button("Start") {
                sound.play()
            }

            Button("Stop") {
                sound.stop()
            }

            Slider(value: $sound.volume)
        }
    }
}

Using this approach you can play and stop the audio on demand, adjust its volume, repeat count, and more.

Option 3: Bind playback to program state

If you want to have a sound start or stop playing based on the state of your program, use the sound() modifier on a SwiftUI view, attaching a binding to your state:

struct ContentView: View {
    @State private var isPlaying = false

    var body: some View {
        Button {
            isPlaying.toggle()
        } label: {
            Image(systemName: isPlaying ? "speaker.wave.3" : "speaker")
        }
        .sound("example.mp3", isPlaying: $isPlaying)
    }
}

Option 4: Manage it yourself

If you want to prepare a sound but not actually play it, call prepare(sound:) instead to receive back an AVAudioPlayer that you can then manipulate and play as you need:

Button("Play Sound") {
    let player = prepare(sound: "example.mp3")
    // configure as needed, then play when ready
}

Important: It is your responsibility to store the player object returned from prepare(sound:), and play it when needed. If you don't store the returned object it will be destroyed immediately, and nothing will play.

Stopping sounds

Once a sound is playing, stopping it depends on how you played it:

  • If you used play(sound:) you can use stop(sound: "example.mp3") to stop all instances of example.mp3, or stopAllManagedSounds() to stop all sounds that were played using play(sound:).
  • If you created an instance of SubsonicPlayer, you can call stop() on it whenever you want.
  • If you used the sound() modifier to play your sound based on the state of your program, that same state is also responsible for stopping the sound.
  • If you used prepare(sound:) you are responsible both playing and stopping the sound yourself.

Important: Calling stopAllManagedSounds() will have no effect on sounds that were not created using play(sound:) – that includes any sounds created using SubsonicPlayer, any sounds you created using prepare(sound:), and any sounds that are playing using the sound() modifier.

Options

When using play(sound:) and the sound() modifier, there are various extra parameters you can provide if needed:

  • bundle controls which bundle contains your sound file. This defaults to Bundle.main.
  • volume controls the relative loudness of the sound, where 0 is silence and 1 is maximum volume. This defaults to 1.
  • repeatCount controls how many times the sound should be repeated. Set to 0 to play the sound once, set to 1 to play the sound twice, and so on, or use .continuous to repeat the sound indefinitely. This defaults to 0.

The sound() modifier also has an extra option, playMode, which controls what happens when the sound resumes playing after it was previously stopped. This is set to .reset by default, which means when a sound resumes playing it will start from the beginning, but you can use .continue to have sounds pick up where they left off.

You can also pass a customΒ bundle when using prepare(sound:), and again it defaults to Bundle.main.

If you're using SubsonicPlayer, you can set the bundle, volume, repeat count, and play mode in the initializer, but the latter three are also variable properties you can adjust dynamically.

Credits

Subsonic was created by Paul Hudson, and is copyright Β© Paul Hudson 2021. Subsonic is licensed under the MIT license; for the full license please see the LICENSE file.

If you find Subsonic useful, you might find my website full of Swift tutorials equally useful: Hacking with Swift.

More Repositories

1

ControlRoom

A macOS app to control the Xcode Simulator.
Swift
5,610
star
2

HackingWithSwift

The project source code for hackingwithswift.com
Swift
5,607
star
3

Unwrap

Learn Swift interactively on your iPhone.
Swift
2,265
star
4

Inferno

Metal shaders for SwiftUI.
Metal
2,238
star
5

wwdc

WWDC Community: Learning and sharing together
1,972
star
6

Sitrep

A source code analyzer for Swift projects.
Swift
1,294
star
7

CodeScanner

A SwiftUI view that is able to scan barcodes, QR codes, and more, and send back what was found.
Swift
930
star
8

Vortex

High-performance particle effects for SwiftUI.
Swift
910
star
9

whats-new-in-swift-5-0

An Xcode playground that demonstrates the new features introduced in Swift 5.0.
Swift
731
star
10

Ignite

A static site generator for Swift developers.
Swift
707
star
11

Sourceful

A syntax highlighting source editor for iOS and macOS using UITextView and NSTextView.
Swift
683
star
12

ShaderKit

A library of fragment shaders you can use in any SpriteKit project.
GLSL
655
star
13

SwiftOnSundays

Completed projects for the Swift on Sundays livestream series
Swift
635
star
14

simple-swiftui

A collection of small SwiftUI sample projects.
Swift
634
star
15

Brisk

A proof of concept scripting library for Swift
Swift
503
star
16

SwiftGD

A simple Swift wrapper for libgd
Swift
448
star
17

VisualEffects

A semi-official SwiftUI wrapper for UIVisualEffectView
Swift
354
star
18

whats-new-in-swift-5-5

Swift
312
star
19

swiftui-changelog

A repository to track changes in the SwiftUI generated interface.
Swift
258
star
20

macOS

The project source code for Hacking with macOS.
Swift
239
star
21

whats-new-in-swift-4-1

An Xcode playground that demonstrates the new features introduced in Swift 4.1.
Swift
221
star
22

TapStore

Code for a YouTube video on UICollectionView.
Swift
162
star
23

NeumorphismSwiftUI

Code to accompany my article on this topic.
Swift
139
star
24

whats-new-in-swift-5-3

An Xcode playground that demonstrates the new features introduced in Swift 5.3.
Swift
127
star
25

iDine

Source code for my SwiftUI introduction tutorial.
Swift
126
star
26

whats-new-in-swift-5-1

An Xcode playground that demonstrates the new features introduced in Swift 5.1.
Swift
121
star
27

whats-new-in-swift-5-8

Swift
120
star
28

whats-new-in-swift-4-2

An Xcode playground that demonstrates the new features introduced in Swift 4.2.
Swift
116
star
29

Sharpshooter

A tiny Xcode extension for people who debug with print().
Swift
115
star
30

whats-new-in-swift-5-7

Swift
115
star
31

100

A list of solutions for the 100 Days of Swift challenge
113
star
32

whats-new-in-swift-5-4

Swift
100
star
33

HWSTranslation

A community project to translate free Swift tutorials
99
star
34

watchOS

The project source code for Hacking with watchOS.
Swift
98
star
35

vapor-clean

A Vapor 3 template with no additional cruft.
Swift
97
star
36

whats-new-in-swift-5-2

An Xcode playground that demonstrates the new features introduced in Swift 5.2.
Swift
95
star
37

AppleTime

A tiny program to use 9:41 in your iOS simulators.
Swift
92
star
38

whats-new-in-swift-5-6

Swift
91
star
39

HackingWithReact

The project source code for hackingwithreact.com
JavaScript
72
star
40

iTour

Source code for my SwiftData introduction tutorial.
Swift
67
star
41

Placeholder

Place temporary images in your iOS app showing the size of the available space.
Swift
56
star
42

Trekr

Companion code for a YouTube livestream.
Swift
54
star
43

FaceFacts

Source code for my SwiftUI + SwiftData tutorial.
Swift
51
star
44

Markdown

A small and fast Markdown parser library for Swift.
Swift
44
star
45

SwiftOverCoffee

Links to solutions for Swift over Coffee challenges
39
star
46

SwiftSlug

A simple package to convert strings to URL slugs.
Swift
38
star
47

Playmaker

Create Xcode playgrounds from Markdown.
Swift
35
star
48

IgniteStarter

A starter template for the Ignite static site generator.
Swift
33
star
49

tvOS

The project source code for Hacking with tvOS.
Swift
30
star
50

IgniteSamples

Sample code for the Ignite static site generator.
Swift
23
star
51

kitura-vs-vapor

A side-by-side comparison of two popular server-side Swift frameworks.
Swift
22
star
52

Cgd

A small Swift package exposing libgd to Swift.
Swift
20
star
53

super-powered-string-interpolation

Swift
18
star
54

SamplePackage

A test package for Swift Package Manager.
Swift
18
star
55

betterbeeb

Better Beeb
Swift
16
star
56

HowToInstrument

A deliberately broken app to help demonstrate Instruments.
Swift
14
star
57

BioBlitz

Code created during my birthday livestream 2022.
Swift
14
star
58

Paraphrase

A trivial app for storing and viewing famous quotes
Swift
12
star
59

DadJokes

The code from my try! Swift NYC 2019 talk.
Swift
10
star
60

homebrew-brew

Homebrew formulae.
Ruby
8
star
61

whats-new-in-swift-6-0

Swift
6
star
62

Paraphrase-Improved

Swift
4
star
63

switcharoo

Switcharoo
Python
4
star
64

easyoc

EasyOC
Objective-C
4
star
65

whats-new-in-swift-5-10

Swift
1
star