SwiftySound is a simple library that lets you deal with Swift sounds easily

Overview

SwiftySound

CocoaPods License CocoaPods CocoaPods Platforms Carthage Compatible SPM ready Build status codecov codebeat Codacy

Overview

SwiftySound is a simple library that lets you deal with Swift sounds easily.

Static methods
Sound.play(file: "dog.wav")
Sound.play(url: fileURL)

More advanced example:

Sound.play(file: "dog", fileExtension: "wav", numberOfLoops: 2)

The above will play the sound three times.

Specify a negative number of loops to play the sound continously in an infinite loop:

Sound.play(file: "dog", fileExtension: "wav", numberOfLoops: -1)

Stop currently playing sounds:

Sound.stopAll()

Enable/disable all sounds:

Sound.enabled = true
Sound.enabled = false

The value of Sound.enabled property will be automatically persisted in UserDefaults and restored on the next launch of your app.

Change sound categories. SwiftySound provides a simple way of changing sound category:

Sound.category = .ambient

This changes the category of the underlying shared AVAudioSession instance. The default value is SoundCategory.ambient. Due to AVAudioSession architecture, this property is not available on macOS.

Creating instances of Sound class

You can also create an instance of a Sound class and store it somewhere in your app.

let mySound = Sound(url: fileURL)
mySound.play()

Creating an instance has more benefits like the ability to adjust the volume and playback callbacks.

Change the volume

You can change the volume of each Sound instance.

mySound.volume = 0.5

The value of volume property should be between 0.0 and 1.0, where 1.0 is the maximum.

Callbacks

You can pass a callback to the play method. It will be played after the sound finished playing. For looped sounds, the callback will be called once after the last loop has been played.

mySound.play { completed in
    print("completed: \(completed)")
}
The callback is not called if the sound was stopped, interrupted or in case of a playback error.

Features

  • Playing single sounds
  • Loops
  • Infinite loops
  • Playing the same sound multiple times simultaneously
  • Stopping all sounds with a global static method
  • Ability to pause and resume
  • Adjusting sound volume
  • Callbacks
  • Global static variable to enable/disable all sounds

Requirements

  • Swift 5
  • Xcode 10.2 or later
  • iOS 8.0 or later
  • tvOS 9.0 or later
  • macOS 10.9 or later

For Xcode 8 and Swift 3 support, please use SwiftySound version 0.7.0. For Xcode 9 and Swift 4 support, please use SwiftySound version 1.0.0.

Installation

Installation with CocoaPods

CocoaPods is a dependency manager which automates and simplifies the process of using third-party libraries in your projects. See the Get Started section for more details.

Podfile

platform :ios, '8.0'
use_frameworks!
pod 'SwiftySound'

Installation with Carthage

Carthage is a lightweight dependency manager for Swift and Objective-C. It leverages CocoaTouch modules and is less invasive than CocoaPods.

To install with carthage, follow the instruction on Carthage

Cartfile

github "adamcichy/SwiftySound"

Installation with Swift Package Manager

The Swift Package Manager is a tool for managing the distribution of Swift code. Just add the url of this repo to your Package.swift file as a dependency:

import PackageDescription

let package = Package(
    name: "YourPackage",
    dependencies: [
        .Package(url: "https://github.com/adamcichy/SwiftySound.git",
                 majorVersion: 0)
    ]
)

Then run swift build and wait for SPM to install SwiftySound.

Manual installation

Drop the Sound.swift file into your project, link against AVFoundation.framework and you are ready to go.

Licenses

SwiftySound is licensed under the MIT License.

Comments
  • Sound doesn't play when created as an object

    Sound doesn't play when created as an object

    First: thank you for this library! Super helpful. Second: I may be doing something very silly.

    I have a sound in an mp3 file. When I play it using the Sound class, it works:

    let audioUrl = "path/that/works.mp3"
    Sound.play(url:audioUrl)
    

    However, if I try to play from an instance of a sound object, it does not actually play any sound (and does not ever call back a completion event):

    let audioUrl = "path/that/works.mp3"
    let mySound = Sound(url: audioUrl)
    mySound!.play()
    

    Any clues as to what might be going on? When I debug and follow the control flow it seems to be calling all the right things, ultimately ending on return play() in line 353 of Sound.swift

    Thoughts appreciated.

    opened by slifty 5
  • Crash in Playing

    Crash in Playing

    Any idea on what's happening?

    For some reasons, we implement our code like this.

                DispatchQueue(label: "com.staysorted.soundfx").async {
                    Sound.play(file: sound.filename)
                }
    
    Crashed: com.staysorted.soundfx
    0  AVFAudio                       0x19d7497b8 AVAudioPlayerCpp::AQOutputCallbackCore(OpaqueAudioQueue*, AudioQueueBuffer*) + 432
    1  AVFAudio                       0x19d748d8c AVAudioPlayerCpp::prepareToPlayQueue() + 224
    2  AVFAudio                       0x19d748ee4 AVAudioPlayerCpp::playQueue(AudioTimeStamp const*) + 112
    3  AVFAudio                       0x19d7477c0 AVAudioPlayerCpp::play() + 84
    4  AVFAudio                       0x19d7108e0 -[AVAudioPlayer play] + 52
    5  SwiftySound                    0x101602f4c protocol witness for Player.play() -> Bool in conformance AVAudioPlayer (Sound.swift)
    6  SwiftySound                    0x1016023f8 Sound.play(numberOfLoops : Int) -> Bool (Sound.swift:153)
    7  SwiftySound                    0x101605124 specialized static Sound.play(url : URL, numberOfLoops : Int) -> Bool (Sound.swift:195)
    8  SwiftySound                    0x101602640 static Sound.play(file : String, fileExtension : String?, numberOfLoops : Int) -> Bool (Sound.swift)
    9  OneReminder                    0x1002a08a0 ORSoundFxManager.(playSound(ORSoundFx) -> ()).(closure #1) (ORSoundFxManager.swift:198)
    10 libdispatch.dylib              0x1824069e0 _dispatch_call_block_and_release + 24
    11 libdispatch.dylib              0x1824069a0 _dispatch_client_callout + 16
    12 libdispatch.dylib              0x182414ad4 _dispatch_queue_serial_drain + 928
    13 libdispatch.dylib              0x18240a2cc _dispatch_queue_invoke + 884
    14 libdispatch.dylib              0x182414fa8 _dispatch_queue_override_invoke + 344
    15 libdispatch.dylib              0x182416a50 _dispatch_root_queue_drain + 540
    16 libdispatch.dylib              0x1824167d0 _dispatch_worker_thread3 + 124
    17 libsystem_pthread.dylib        0x18260f100 _pthread_wqthread + 1096
    18 libsystem_pthread.dylib        0x18260ecac start_wqthread + 4
    
    opened by harryworld 5
  • Swift Package manager can not import into Xcode (11b3)

    Swift Package manager can not import into Xcode (11b3)

    Xcode SPM import error:

    The package dependency graph can not be resolved, possibly because of these requirements: https://github.com/adamcichy/SwiftySound.git — 1.1.0..<2.0.0

    Using WWDC19 Beta 3 across the board.

    opened by LordAndrei 4
  • Seems to be a maximum number of different sounds able to be played

    Seems to be a maximum number of different sounds able to be played

    I'm creating a soundboard that has 112 sounds right now, however when I try to play them all one after another they stop working after the 50th sound. No matter what order I play the sounds, after 50 they stop working. Is there a max amount of sounds that can load, and if so how can I increase that limit?

    opened by RobertFiorentino 4
  • no sound on iOS 11

    no sound on iOS 11

    Our app plays sound on iOS 10, but after upgrade to iOS 11, the mp3s don't have any sound. They do seem to be "playing" as we can time aspects of the app to see that a event doesn't happen until after the file should have completed. But no volume. We can hear the sound on the simulator but not the iPad or iPhone device. We've played with the volume setting and a few others but no luck. Debugging doesn't show any errors. The sound objects look about right. Any ideas to debug this?

    opened by jhancock 4
  • Sound Randomly Stops

    Sound Randomly Stops

    Hi,

    I'm using SwiftySound and I've noticed that when I play a sound, it occasionally stops out of a sudden. It does not always occur, only sometimes. When it does, it seems to happen at a random duration and is unpredictable.

    I'm using Sound.play(file: "Timer.m4a") to play and Sound.stop(file: "Timer.m4a") to stop the sound. I've uploaded the audio file here.

    Any help would be much appreciated, thanks!

    opened by aabosh 4
  • Sound.Category Not Working On IOS 14

    Sound.Category Not Working On IOS 14

    On IOS 14 (maybe earlier versions as well) changing the AVAudioSession's category utilizing Sound.category doesn't seem to work as intended.

    If you would like to disable playing simultaneous audio tracks and want to switch to only playing one at a time, you should be able to set the category to .playback or .soloAmbient to disable "mixing". When changing the category however, audio still mixes.

    By the way, loving this library thus far as it has saved me a lot of time, thank you!

    opened by emtjoshhart 3
  • Inconsistencies between static methods and instances

    Inconsistencies between static methods and instances

    This is working for me:

    let fileURL = Bundle.main.url(forResource: "MyMusic", withExtension: "mp3")!
    Sound.play(url: fileURL) // Music plays
    

    While this is not

    let fileURL = Bundle.main.url(forResource: "MyMusic", withExtension: "mp3")!
    let mySound = Sound(url: fileURL)!
    mySound.play()
    

    I'm running both these snippets in the exact same spot in my code, so I have no idea why one would work and the other wouldn't. May very well be user error, but I think I'm following the documentation correctly.

    opened by trentjones21 2
  • Cannot increase or decrease playersPerSound int

    Cannot increase or decrease playersPerSound int

    I installed this with cocoa pods. I'm not sure if I'm doing anything wrong but when I go into the sound.swift file and try to change the playersPerSound over 5 or under 5 it doesn't reflect that change in the app after I build it, it only plays 5 at the same time. I want it at 20, here's what I changed the line of code to look like: public static var playersPerSound: Int = 20 {

    opened by ipoogleduck 2
  • volume control hassles

    volume control hassles

    Trying to do volume control when playing but the only way to do that is through creating a new instance that I then have to keep track of since if it goes out of scope it doesn't play. Perhaps I'm doing it wrong. Ideally I would like to do something like Sound.play(url: url, withVolume:0.3 ....

    Is this possible?

    opened by artangco 2
  • Why `init?(name: String)` was removed in 1.0.0?

    Why `init?(name: String)` was removed in 1.0.0?

    Up to 0.7.0 I could load sound files for xcassets. Now it is hard and cumbersome to manually create a URL out of a NSDataAsset.

    Is there a particular reason for removing this? Would it be bad to at least keep init?(data: Data)?

    Thanks!

    opened by rivera-ernesto 2
  • How to prevent Error Code -42

    How to prevent Error Code -42

    In my game I use different sounds for enemies.

    After a specific time the player is not able to play any new sounds and also the older ones might not finish playing or are interrupted.

    is there a way to just clean all the memory from sounds so it can start adding sounds anew?

    e.g. after every battle a function can be run that all old sounds are removed?

    i also have some predefined sounds in a func, should I remove this, or would this not matter? like:

    func playTrapSound() { Sound.play(file: "hitTrap", fileExtension: "mp3", numberOfLoops: 0) }

    Any help appreciated!

    opened by BenNathanaelTse 1
  • After the 5th time playing a sound doesn't start from 0:00.

    After the 5th time playing a sound doesn't start from 0:00.

    Hello,

    I was running into the issue that after I play a sound for the fifth time by clicking a button using the Sound.play(file: "X.mp3") method, it doesn't start from it's very beginning and just seems to play at a random point.

    Best regards

    opened by VotusX 3
Owner
Adam Cichy
Mobile developer mainly focused on iOS. http://adamcichy.info
Adam Cichy
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

Luis Cárdenas 89 Nov 21, 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
Analyser BPM in Swift for your music/sounds/records, whatever..

BPM-Analyser Analyser BPM in Swift for your music/sounds/records, whatever.. Powered with Superpowered Preview: How To: Copy theese files to your proj

Gleb Karpushkin 71 Dec 24, 2022
iOS application for finding formants in spoken sounds

FORMANT PLOTTER Buy on the App Store: https://itunes.apple.com/us/app/formant-analyzer/id799183655?mt=8&uo=4&at=11l6hc&ct=fnd This is an iOS project t

William Entriken 51 Dec 25, 2022
Background sounds feature from iOS 15 on iOS 11+

Tranquil Background sounds feature from iOS 15 on iOS 11+ Only physically tested on iOS 14.3 and iOS 12.1.2, but it should support iOS 11 - iOS 15.x (

Dana Buehre 4 Dec 15, 2022
Recording Indicator Utility lets you turn off the orange microphone recording indicator light for live events and screencasts.

Recording Indicator Utility Recording Indicator Utility lets you turn off the orange microphone recording indicator light, making it ideal for profess

Tyshawn Cormier 121 Jan 1, 2023
🗣Voice overlay helps you turn your user's voice into text, providing a polished UX while handling for you the necessary permissions

Voice overlay helps you turn your user's voice into text, providing a polished UX while handling for you the necessary permissions. It uses i

Algolia 490 Dec 19, 2022
Nobetci Eczacim is open-source App Store Application which users can get pharmacy information and location easily and safely.

Pharmacy-On-Duty Nobetci Eczacim Project Description This project designed for make it easier for people to search for a pharmacy on duty. App Store A

Mert Demirtas 5 Sep 19, 2022
An advanced media player library, simple and reliable

About The SRG Media Player library provides a simple way to add universal audio / video playback support to any application. It provides: A controller

SRG SSR 145 Aug 23, 2022
SimplePlayer - A simple application to fetch songs from iTunes Library by searching song's artist

SimplePlayer is a simple application to fetch songs from iTunes Library by searching song's artist.

Maria Angelina 0 Jan 30, 2022
A tiny menu bar app detecting the chords of the songs you are listening on iTunes or Spotify.

ChordDetector A tiny menu bar app that listens iTunes and Spotify to detect chords of songs! Demo Features iTunes and Spotify support. Saves up to 20

Cem Olcay 72 Dec 26, 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
Squares - a toy drum machine which you can control by multi touch capabilities of your track pad

Squares Squares is a toy drum machine which you can control by multi touch capab

Umur Gedik 7 Oct 3, 2022
Analyzes the news as you listen to them

News Analyzer What It Does News Analyzer, let you listen to English news, see the text and let you analyze what you have heard. The analysis contains,

Ethan 4 Feb 10, 2022
An app to get you the latest and the trending news based on your location.

Newsline Link to APK : http://bit.ly/newslineapp Newsline is an android application made with flutter which makes use of NewsAPI.org to fetch and serv

Ayush Shekhar 19 Nov 11, 2022
A simple Spotify lyrics viewer menu bar app for macOS in Swift 3

lyricsify This is a simple macOS menu bar application that shows you the lyrics of current playing spotify track. All the lyricses are from Wikia webs

Mohamad Jahani 85 Dec 31, 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
Simplest MIDI Swift library

WebMIDIKit: Simplest Swift MIDI library ###Want to learn audio synthesis, sound design and how to make cool sounds in an afternoon? Check out Syntoria

null 131 Dec 4, 2022