Subsonic is a small library that makes it easier to play audio with SwiftUI

Related tags

Audio Subsonic
Overview

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: {
            if isPlaying {
                Image(systemName: "speaker.wave.3")
            } else {
                Image(systemName: "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.

You might also like...
An iOS app that visually clones Spotify's app and consumes the official Spotify's Web API to show(and play) songs, podcasts, artists and more.
An iOS app that visually clones Spotify's app and consumes the official Spotify's Web API to show(and play) songs, podcasts, artists and more.

SpotifyClone An iOS app that visually clones Spotify's app and consumes the official Spotify's Web API to show(and play) songs, podcasts, artists and

SPlayer - play mp3/pm4

SPlayer - play mp3/pm4

Soundable allows you to play sounds, single and in sequence, in a very easy way

Overview Soundable is a tiny library that uses AVFoundation to manage the playing of sounds in iOS applications in a simple and easy way. You can play

MusicalInstrument - Play musical instrument in just few lines of swift code

MusicalInstrument Play musical instrument in just few lines of swift code. Requi

Play and share sound inserts from Medo e Delírio em Brasília, a Brazilian podcast.
Play and share sound inserts from Medo e Delírio em Brasília, a Brazilian podcast.

Play and share sound inserts from Medo e Delírio em Brasília, a Brazilian podcast.

AudioKit is an audio synthesis, processing, and analysis platform for iOS, macOS, and tvOS.

AudioKit is an audio synthesis, processing, and analysis platform for iOS, macOS (including Catalyst), and tvOS. Installation To add AudioKit

AudioPlayer is syntax and feature sugar over AVPlayer. It plays your audio files (local & remote).

AudioPlayer AudioPlayer is a wrapper around AVPlayer. It also offers cool features such as: Quality control based on number of interruption (buffering

AudioPlayer is a simple class for playing audio in iOS, macOS and tvOS apps.
AudioPlayer is a simple class for playing audio in iOS, macOS and tvOS apps.

AudioPlayer AudioPlayer is a simple class for playing audio in iOS, macOS and tvOS apps.

FDWaveformView is an easy way to display an audio waveform in your app
FDWaveformView is an easy way to display an audio waveform in your app

FDWaveformView is an easy way to display an audio waveform in your app. It is a nice visualization to show a playing audio file or to select a position in a file.

Comments
  • Suggested Changes by mmmayer

    Suggested Changes by mmmayer

    README: Updated code example Code_Of_Conduct: Updated COC to Version 2.1 SubsonicController: Updated a couple of error messages to include the bundle SubsonicPlayer: Corrected a typo in a comment

    opened by mmmayer 1
Owner
Paul Hudson
Creator of Hacking with Swift, author of books about iOS, macOS, watchOS, and tvOS, public speaker, Rubik's cube enthusiast, and herder of my kids.
Paul Hudson
KeyAudioManager - A swift package to make it a lot easier to play audio in your app

KeyAudioManager A swift package to make it a lot easier to play audio in your ap

Pedro Esli 3 Apr 28, 2022
The Amazing Audio Engine is a sophisticated framework for iOS audio applications, built so you don't have to.

Important Notice: The Amazing Audio Engine has been retired. See the announcement here The Amazing Audio Engine The Amazing Audio Engine is a sophisti

null 523 Nov 12, 2022
AudiosPlugin is a Godot iOS Audio Plugin that resolves the audio recording issue in iOS for Godot Engine.

This plugin solves the Godot game engine audio recording and playback issue in iOS devices. Please open the Audios Plugin XCode Project and compile the project. You can also use the libaudios_plugin.a binary in your project.

null 3 Dec 22, 2022
Beethoven is an audio processing Swift library

Beethoven is an audio processing Swift library that provides an easy-to-use interface to solve an age-old problem of pitch detection of musical signals.

Vadym Markov 735 Dec 24, 2022
YiVideoEditor is a library for rotating, cropping, adding layers (watermark) and as well as adding audio (music) to the videos.

YiVideoEditor YiVideoEditor is a library for rotating, cropping, adding layers (watermark) and as well as adding audio (music) to the videos. YiVideoE

coderyi 97 Dec 14, 2022
A drop-in universal library allows to record audio within the app with a nice User Interface.

IQAudioRecorderController IQAudioRecorderController is a drop-in universal library allows to record and crop audio within the app with a nice User Int

Mohd Iftekhar Qurashi 637 Nov 17, 2022
This app demonstrates how to use the Google Cloud Speech API and Apple on-device Speech library to recognize speech in live recorded audio.

SpeechRecognitionIOS This app demonstrates how to use Google Cloud Speech API and Apple on-device Speech library to recognize speech in live audio rec

Josh Uvi 0 Mar 11, 2022
A small project written with SwiftUI achieves a scrolling effect similar to Apple Music lyrics.

Music Lyrics scrolling animation effect Since the iOS/iPadOS 13 update, Apple has brought a new scrolling lyrics feature to Apple Music. The album im

Huang Runhua 18 Nov 9, 2022
SoundManager - A simple framework to load and play sounds in your app.

SoundManager - A simple framework to load and play sounds in your app.

Jonathan Chacón 3 Jan 5, 2022
The easiest way to prepare, play, and remove sounds in your Swift app!

Chirp The easiest way to prepare, play, and remove sounds in your Swift app! ##Installation ###CocoaPods Installation Chirp is available on CocoaPods.

null 309 Dec 17, 2022