Giter VIP home page Giter VIP logo

jpsvolumebuttonhandler's Introduction

JPSVolumeButtonHandler

JPSVolumeButtonHandler provides an easy block interface to hardware volume buttons on iOS devices. Perfect for camera apps! Used in JPSImagePickerController.

Features:

  • Run blocks whenever a hardware volume button is pressed
  • Volume button presses don't affect system audio
  • Hide the HUD typically displayed on volume button presses
  • Works even when the system audio level is at its maximum or minimum, even when muted

Installation

Swift Package Manager (SPM)

Add: https://github.com/jpsim/JPSVolumeButtonHandler.git (master branch) to your "Package Dependencies" in XCode.

Or add: .package(url: "https://github.com/jpsim/JPSVolumeButtonHandler.git", branch: "master") to your swift package file.

From CocoaPods

Add pod 'JPSVolumeButtonHandler' to your Podfile.

Manually

Drag the JPSVolumeButtonHandler folder into your project and link the MediaPlayer and AVFoundation frameworks to your project.

Usage

Set your blocks to be run when the volume buttons are pressed:

self.volumeButtonHandler = [JPSVolumeButtonHandler volumeButtonHandlerWithUpBlock:^{
	// Volume Up Button Pressed
} downBlock:^{
	// Volume Down Button Pressed
}];

To enable/disable the handler:

// Start
[self.volumeButtonHandler startHandler:YES]; 
// Stop
[self.volumeButtonHandler stopHandler];

To change audio session category (by default AVAudioSessionCategoryPlayAndRecord):

// Set category
self.volumeButtonHandler.sessionCategory = AVAudioSessionCategoryAmbient; 

To change the audio session category options (by default AVAudioSessionCategoryOptionMixWithOthers):

self.volumeButtonHandler.sessionOptions = AVAudioSessionCategoryOptionAllowBluetooth|AVAudioSessionCategoryOptionMixWithOthers;

Note that not all options are compatible with all category options. See AVAudioSession documentation for details.

License

This project is under the MIT license.

jpsvolumebuttonhandler's People

Contributors

apple-ihack-geek avatar atomicbird avatar fitsyu avatar gliyao avatar jeroenvollenbrock avatar joestelmach avatar jondot avatar joshbernfeld avatar jpsim avatar kronik avatar mirceapasoi avatar mrgrauel avatar nolanw avatar nylki avatar rsanchezsaez avatar samyes 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

jpsvolumebuttonhandler's Issues

Carthage

Please can you also support Carthage? :)

different behavior with headphones buttons

When iPhone buttons are pressed and hold the action in volumeButtonHandlerWithUpBlock is repeated.
When using headphone volume buttons to trigger the camera there is only one shot.
Is this a limitation of iOS?
Thank you

Event issue at initialization

Thanks for this awesome library.
I'm facing an issue, at initialization, PSVolumeButtonHandler adjusts the volume to avoid a maximum or minimum state (i suppose that in this state, it will couldn't detect any event on volume buttons).
But when adjusting, it's triggering by itself and call the upBlock or downBlock.

how to avoid that ?

Lost control

Great class!
It worked in my lap counter app as I expected.

However, there are (at least) two cases when it loses the control of volume buttons:

  1. if you visit another app and then get back to your own app
  2. if you blank your display (clicking shortly power button). In my case, the app should register volume buttons even when the display is off (to save battery).

Any ideas how to manage these situations???

Tested on iPhone 5.

regards, Juha

using deprecated method setVolume:

[[MPMusicPlayerController applicationMusicPlayer] setVolume:(float)volume]; is deprecated and we don't know when apple will remove it.
i think there is currently no alternative, but maybe this could be solved in future?
thanks for this nice class

Update Cocoapods

It would be great to update the version found in Cocoapods to include the latest changes.

playing sound while button is pressed

While the volume button is pressed, if some conditions are met I'd like to play a sound. Unfortunately the sound often is kind of cut of. It is quite easy to reproduce, while the volume button is pressed, play a sound AudioServicesPlaySystemSound(self.beepSound). Is it happening because of the other audio session going on? Any idea how to solve it?

first run issue

Hi,
I'm trying to use the code, but can't seem to get it to run.

This is the code:

`
#import "ViewController.h"
#import "JPSVolumeButtonHandler.h"

@interface ViewController ()

@Property (nonatomic,strong) JPSVolumeButtonHandler *volumeButtonHandler;

@EnD

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];
    }

-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self.volumeButtonHandler stopHandler];
[self.volumeButtonHandler startHandler:YES];
[NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(takePhoto)
userInfo:nil
repeats:NO];

}

-(void)takePhoto{
NSLog(@"takePhoto");
self.volumeButtonHandler = [JPSVolumeButtonHandler volumeButtonHandlerWithUpBlock:^{
// Volume Up Button Pressed
NSLog(@"Volume Up Button Pressed");

} downBlock:^{
    // Volume Down Button Pressed
    NSLog(@"Volume Down Button Pressed");
    
}];

}
@EnD
`

Is there more to getting this working than the readme says?

I'm just doing a quick test prototype to make sure that I can in fact respond to volume buttons presses. I installed VolumeButtonHandler via Cocoapods, ensured that my project sees it and implemented the following as a test in ViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];

    self.outputLabel.text = @"";

    self.volumeHandler = [JPSVolumeButtonHandler volumeButtonHandlerWithUpBlock:^{
        self.outputLabel.text = @"  Up!  ";
    } downBlock:^{
        self.outputLabel.text = [self.outputLabel.text stringByAppendingString:@"  Down!  "];
    }];
}

When I load it up on my iPhone6, It doesn't print anything to my label upon pressing vol up or down

Install Via SPM?

Is it possible to install this repo via spm and not cocoapods?

AVF context unavailable nothing happening

Hi there jpsim
While searching the Internet for a volume button handler I stumbled upon your code here.
I really need your code and tried to run it in Xcode but during simulation I get the following message:

2018-04-01 11:11:11.082845-0700 Buttons[11228:255620] [MediaRemote] [AVOutputContext] WARNING: AVF context unavailable for sharedAudioPresentationContext
2018-04-01 11:11:11.087537-0700 Buttons[11228:255620] [MediaRemote] [AVOutputContext] WARNING: AVF context unavailable for +[MRAVOutputContext createOutputContextWithUniqueIdentifier:]

I have to admit that I really do not know objective c but I was pretty sure that I did everything you've said.I've added the frameworks in my settings,too

#import "helloViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "SystemVolumeView.h"

#import "JPSVolumeButtonHandler.h" //here importer

@interface helloViewController ()

@Property (nonatomic,strong) JPSVolumeButtonHandler *volumeButtonHandler;// declared

@EnD

@implementation helloViewController

  • (void)viewDidLoad {
    [super viewDidLoad];

    [self.volumeButtonHandler stopHandler]; // just to make sure but also tried without this line
    [self.volumeButtonHandler startHandler:YES];

}

  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

  • (IBAction)showMessage //click button to see if it works then it should listen for button press
    {
    NSLog(@"Something");
    self.volumeButtonHandler = [JPSVolumeButtonHandler volumeButtonHandlerWithUpBlock:^{
    // Volume Up Button Pressed
    NSLog(@"Volume Up Button Pressed");

    } downBlock:^{
    // Volume Down Button Pressed
    NSLog(@"Volume Down Button Pressed");

    }];}

your code is very crucial for me. I've already implemented this feature for my android app version but I'm struggling with iOS. All other objective c codes on the internet are outdated. they worked until iOS 7.

Thanks in advance.

Calling startHandler:

What is supposed to call startHandler:?
If we are supposed to do that in our code, mind if I make a RP to amend the readme to let people know to do so ?

Initialization prevents bluetooth audio playback

Whenever I start JPSVolumeButtonHandler, sadly bluetooth audio playback stops. I tried setting the option for "AVAudioSessionCategoryOptionAllowBluetooth" but sadly it made no difference. Any idea how best to resolve this?
Thanks.

Does not work in flutter project

I try to use JPSVolumeButtonHandler in a flutter project, but the volume buttons are not detected. This is how I used it:

AppDelegate.swift:

var volumeButtonHandler: JPSVolumeButtonHandler?
volumeButtonHandler = JPSVolumeButtonHandler(up: {self.doSomething()}, downBlock: {self.doSomething()})
volumeButtonHandler?.start(true)
...  
func doSomething() -> Void {  
...  
}

how to cancel the volumn icon?

Thanks for giving us wonderful demo,I use "JPSVolumeButtonHandler" in my app, but I can not understand that when I start my application,there is a system sound icon appear in the center of screen sometimes , not every time , particularly in ios8.
I want to stop it appearing.what should I do? thank you.

Weird bug when used at the same time as an AVCaptureSession

Please see my StackOverflow post for details: http://stackoverflow.com/questions/29312178/cant-call-startrecordingtooutputfileurl-more-than-once-on-instance-of-avcapture

I think JPSVolumeButtonHandler might not be cleaning up after itself properly. If I initialize it once, then I can record videos fine. But if I set it to nil and it deallocates (when my view disappears), and then I initialize it again, I can't record videos anymore (Using AVCaptureMovieFileOutput#startRecordingToOutputFileURL).

Unable to set nil to the JPSVolumeButtonHandle instance.

var volumeButtonHandler = JPSVolumeButtonHandler()
and
override func viewWillDisappear(_ animated: Bool)
{
self.volumeButtonHandler = nil
//Error showing that Nil can not be assign to the type of "JPSVolumeButtonHandler"
}
I am using Xcode 8.2.1 version. let me know a solution for this.

First use permanently dampens some system sounds until app restart

First of all: Thanks a lot for offering and maintaining this very helpful piece of code!

In short: When first creating (and using) an instance of this handler, the handler somehow mutes some system sounds to some degree, e.g., AudioServicesPlaySystemSound(1104). Disabling and releasing the handler does not undo this effect. Only restarting the app resets volume levels to normal. The effect may be slight enough for anyone, who is not heavily relying on other system sounds, to miss it.

Details: I have UIButtons that indicate a press by playing a system sound. At medium volume levels, this sound is quite clearly audible. As soon as a I enable support of volume button taps through this module (as an alternative means to tap those UIButtons, a means that can be switched on and off dynamically), the same sounds are still played, but at significantly reduced volume. The volume also remains at this constant low level when disabling the button handler entirely again.

Furthermore, before creating the first instance of this module, system sounds react to changes in volume (not in a major way, but clearly audible). Once I create a first instance of the handler, volume levels for the system sounds affected remain constant(ly low) no matter the volume level.

Finally, weirdly enough, this unpleasant effect only seems to concern some system sounds (like 1104) but not others (like 1103). There is not a whole lot of fancy in my code and in particular the treatment of different system sounds. So, it seems rather unlikely that the effects described are caused in my code.

I am a fairly long-time user of this module. I notice the effects more pronounced now, because of a more systematic use of system sounds. However, I do believe that I noticed the same effects a year ago already. So, it does seem to me that the volume button handler code does some permanent damage to the system's volume handling for some time.

(I notice another effect where, right after switching the handler on for the first time, the first system sounds that follow are completely dropped or cause a significant delay in app execution up to approximately several 100s of milliseconds. But this effect is even more erratic, so I cannot pinpoint it perfectly yet.)

Any ideas how to fix this? -- And notice that, if you are using this module (a) as always switched on like in a typical camera app or (b) in an app without any significant sound, it will be hard to notice. In my case, it's rather noticeable and confusing to users. Thanks for any reaction!

EDIT: I could add that this is how I play those system sounds:
GlobalUserInitiatedQueue.async {
AudioServicesPlaySystemSound(soundId)
return
}
where
var GlobalUserInitiatedQueue: DispatchQueue {
return DispatchQueue.global(qos: .userInitiated)
}

some volume events missed (xcode 13)

This works pretty well for me on ios 15.6 but sometimes an up or down event doesn't fire. I'm trying to make a stopwatch app and sometimes I have to press volume up or volume down twice to get the event to fire.

Any tips on if this can be fixed/improved or maybe I'm doing something wrong?

import SwiftUI
import JPSVolumeButtonHandler

struct ContentView: View {
    @State private var volumeHandler: JPSVolumeButtonHandler?
    var body: some View {
        ZStack {
            Text("Hello World")
        }
        .onAppear {
            volumeHandler = JPSVolumeButtonHandler(up: {
                print("up")
            }, downBlock: {
                print("down")
            })
            volumeHandler?.start(true)
        }
        .onDisappear {
            volumeHandler?.start(false)
        }
    }
}

Is it allowed?

Hi there thank you very mich jps for providing your code. Point is, I‘m at the end of m app‘s development.It‘s a game and release is planned near the end of june. It works all great but now worries start to come that apple could eventually ban it. But please give me some hope. This code should be fine to apple,or? And besides that, the usage of the volume buttons is NOT mandatory in my game but provide help. And lets be honest for some games the buttons are great. Is there a chance that apple will accept my game as it is cause the button feature is great and if people dont like it-they dont have to. Is this a good reason to keep it? Besides that: Camera apps make use of the buttons(IF a cameraman wants it he can smash the button like crazy), a few stop watch apps also have this feature implementet. Apple should not come to me and say that their (the other apps) usage of the buttons is less and therefore „healthy and accepteable“. My game is as well. Thank‘s for reading.

Ps i found this online :
https://forum.unity.com/threads/using-volume-buttons-as-additional-controls-in-game.153966/

It seems like apps have been rejected because they used some sort of private api. Is jpsvolumebuttonhandler with a public api- therefore the chances of being rejected should be minimal?

iPhone X down button issues

Hello!
TY for your work!
When I'm working my device (iPhone 7) all work is good. But when I'm testing on iPhone X I have next case:
When i pressed down sound value button few time, It's not handled. It's a magic count, sometimes 3 or 5. If need i can send proofs.
But up sound value button working is correct!

Headset vol buttons?

Is it possible to tweak the code to make it work with a Bluetooth headset?
In it's current state it does not.

Outdated cocoapods

The code in the repo doesn't appear to match the code in the cocoapod. Is it not the most recent version?

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.