Giter VIP home page Giter VIP logo

swiftysound's Introduction

SwiftySound

CocoaPods License CocoaPods CocoaPods Platforms Carthage Compatible SPM ready codebeat

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 15 or later
  • iOS 12.0 or later
  • tvOS 12.0 or later
  • macOS 10.13 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. For Xcode 10 and iOS 9 support, please use SwiftySound version 1.2.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, '12.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.

swiftysound's People

Contributors

adamcichy avatar fassko avatar jeehut avatar naeemshaikh90 avatar piemonte avatar rivera-ernesto avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swiftysound's Issues

completion block is only called once

I created an instance of a sound and when I need to play it again I'm using the same instance to replay it. What I've noticed that is that if I have a completion block for this sound instance the completion block is only called the first time the sound is played. If I play the sound again the completion block is not called again.

Crash in iOS 11 GM

Sound init?(url: URL) is crashing when loading a sound in iOS 11 GM. It is called like this:

scanSound = Sound(url: Bundle.main.url(forResource: "beep-sound", withExtension: "mp3")!)

The file exists and the URL is not nil.

is it possible to use it with a PageControl?

Hi
Is it possible to use SwiftySound with a pageControl? I mean for example launching a sound when someone swipe to a new page, without having to press a play button? thx for your feedback on that

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.

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!

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

How to crossfade?

Is there a way to crossfade a track when its looped? I need my tracks to sound like infinite.

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!

Crackle and pops in playing sounds on iPhone

Hi!
I have distorted sounds when playing for instance an music track with multiple fx sounds at the same time. Create for instance 5 buttons and tap them quickly randomly. A brute cradling noise will appear. My guess it is not from your SwiftySound. Maybe some brick wall limiting in AVFoundation? Maybe memory issue? Turn off noise canceling on the device helps. But doesn't solve all. Types of audio format doesn't help. Different types of setting for the AVAudioSession also doesn't help. Any tips?
regards,
hj

Xcode 9.2 shows build error but compiles

This may not be an issue, for my part, so I confirmed the problem in the example in this repo.

Whether or not the code conversion process is performed, the example code (using either the original version 0.5 or the latest 0.7), there is an error, but the build will still compile. Using the pod in a custom project has this same issue:

import SwiftySound results in "Cannot load underlying module for 'SwiftySound'"

The example works in the simulator, however, as does a custom project also runs on a device.

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?

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

Small delay when playing a sound for the first time

Hey, first of all thanks for your work, really neat wrapper for playing sounds!

I'm building a metronome and I noticed that there is a small delay when playing a sound for the first time (or more specific: when calling play() the first time on either the Sound class or a Sound object).
Currently I circumvent this issue by playing a sound and immediately stopping it in my viewDidLoad().

If you need more information, drop me a message. Cheers!

Bug in Counter design?

Because you call the following code where you do, any code that runs after it referencing counter will be off by 1 when calling (players[counter]) directly again.

let player = players[counter]
counter = (counter + 1) % players.count

For example if you want to expose the var currentTime in SwiftySound you would have to do the following:

public var currentTime: TimeInterval {
        get {
            print("in swifty currentTime: ", self.players**[counter - 1]**.currentTime)
            print(self.players[counter - 1].currentTime)
            return self.players[counter - 1].currentTime
        }
        set {
            
        }
    }

I think that may be why you're iterating through the entire array of players?

(sorry for spamming your repo with questions :).

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?

Playback time

Would it be possible to include an elapsed time in this library, so even if the sound is being looped you can see how long it has been playing for?

Play file starting from certain duration

Its great we've exposed capturing duration of played file. Can we pass duration back to the file before playing it to restart playing from an supplied duration?

Pause And Resume?

Awesome library! Do you think you can further improve with pause and resume method? Thanks!

Fade option on stopping all playing files

This is more of a feature request:

Would it be possible to add a fade out option with a parameter for how long the fade out should be when calling the stopall function?

The use cases would be when using the loop function for multiple playing files you may want to fade out those sounds instead of stopping them at once.

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.

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!

Not able to play sound when using play method's completion handler.

It works when I use the class method.

Sound.play(file: "ding.wav")

But it doesn't work when I use the code below.
I tested on multiple devices.

        guard let soundUrl = Bundle.main.url(forResource: "ding", withExtension: "wav") else {
            print("error with ding url")
            return
        }
        guard let mySound = Sound(url: soundUrl) else {
            print("error with my sound object")
            return
        }
    
       let didPlay = mySound.play() {
            completed in
            print("completed: \(completed)")
        }

        // prints true
        print("didPlay: \(didPlay)")

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!

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?

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 {

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.