iOS programming to modify system volume

Source: Internet
Author: User

The iOS avfoundation framework provides basic audio and video playback tools, and we can basically do most of the audio and video playback tasks by providing the classes. However, in the processing of output volume of audio playback, Apple's strategy is more conservative. Although Avplayer and Avpaudiolayerzhe these classes provide volume adjustment, these volume controls are app-level controls. The benefit is that the volume adjustment is independent of the system volume and does not affect the system volume when resized. But sometimes we might want to change the system volume so that if the system volume is too low, the app won't be able to adjust the volume significantly when the sound is tuned. In general, there are several ways to adjust the system volume:

Note: Modifying the system volume does not see the effect on the emulator, it must be debugged with a real machine to see the effect!

Using Mpvolumeview

This method is Apple's official recommendation. Mpvolumeview is a UI component in the media Player framework that directly contains control over the system volume and audio mirroring routing of Airplay devices. It contains a mpvolumeslider subview to control the volume. This mpvolumeslider is a private class, and we cannot create this class manually, but this class is a subclass of UISlider. The use of Mpvolumeview is simple, just add it to a parent view, give the parent view the appropriate size, and then create the Mpvolumeview sample, add it to the parent view, Apple's Official Document 1 has the sample code to refer to.

The disadvantages of this method are as follows:

    • The UI can be customized to a low degree. Mpvolumeview only provides a limited number of ways to customize the style of the slider and route button, and it can be solved by simply changing the image. If you want to change the slider operation to a button or other UI component, that's not possible.
    • There is no additional volume control API. there is no direct operating system volume available in the public API for iOS so far, so modifying the system volume can only use this UI component.

If you also want to add gestures to the UI to control the volume, this direct use of mpvolumeview is not possible, then there is no way to bypass this restriction? There is still some way.

Programming for System volume adjustment

In the previous section we mentioned the Mpvolumeview this component, there is a subview to control the volume, that is, Mpvolumeslider. In fact, we can go through the subviews of the Mpvolumeview instance to get an instance of Mpvolumeslider, and thus the operating system volume through this UI component.

Operating system volume via an instance of Mpvolumeslider

We start by creating a mpvolumeview and then traversing the Mpvolumeslider to find out the instance. This example provides the setvalue:animated: method to set the system volume. We can also get the current system volume by volumeslider.value this property. The specific code is as follows:

?
1234567891011121314151617 MPVolumeView *volumeView = [[MPVolumeView alloc] init];UISlider* volumeViewSlider = nil;for (UIView *view in [_instance.volumeView subviews]){    if ([view.class.description isEqualToString:@"MPVolumeSlider"]){        volumeViewSlider = (UISlider*)view;        break;    }}// retrieve system volumefloat systemVolume = volumeViewSlider.value;// change system volume, the value is between 0.0f and 1.0f[volumeViewSlider setValue:1.0f animated:NO];// send UI control event to make the change effect right now.[volumeViewSlider sendActionsForControlEvents:UIControlEventTouchUpInside];

The above code shows how to get and modify the system volume, noting that the volume value is a floating-point number between 0 and 1.

There's a problem! I don't like the system eject volume prompt

The above programming method can be perfect to adjust the system volume, but each change will pop up the system notification box to inform:

Sometimes this kind of hint we may not need, then how to cancel out this hint? In fact, Mpvolumeview does not provide any interface to adjust whether the system volume prompts need to be displayed. But we found that when Mpvolumeview is in the hierarchy of the current view, the system does not display a volume hint . Well, then, let's just make sure two points are done:

    • The Mpvolumeview view is in a place that is invisible on the screen, such as under an opaque view, or a non-visible area of the view, a common practice is to set the frame of the view to a place outside the area, such as Volumeview.frame = CGRectMake (-1000,-100, 100, 100);
    • Make sure that the hidden property value for the Mpvolumeview view is no. Because when hidden is yes, a hint is also popped.
I've changed the system volume, but not through my UI.

Another possibility is that the user himself adjusts the volume through the Hardware's volume Adjustment button (located on the side of the device), which can cause problems with your business logic because you only write callbacks for your app UI, so how do you add callbacks for hardware button events? We can use Notification Center to do this.
Only the Avsystemcontroller_systemvolumedidchangenotification event can be monitored here. The specific code is as follows:

    • First add the code to listen for events during the resource loading phase

?
1234567891011121314 NSError *error;// Active audio session before you listen to the volume change event.// It must be called first.// The old style code equivalent to the line below is://// AudioSessionInitialize(NULL, NULL, NULL, NULL);// AudioSessionSetActive(YES);//// Now the code above is deprecated in iOS 7.0, you should use the new// code here.[[AVAudioSession sharedInstance] setActive:YES error:&error];// add event handler, for this example, it is `volumeChange:` method[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeChanged:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];

    • Then implement the event callback method

?
1234 - (void)volumeChanged:(NSNotification *)notification{    // service logic here.}

    • Finally, remember to cancel the event listener when the resource is recycled.

?
1234 - (void)dealloc{    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AVSystemController_SystemVolumeDidChangeNotification"object:nil];}

This way, each time the user adjusts the volume using the hardware button, the logic you write is also executed.

All of the above solutions, except for the first one, are unofficial, hack-nature methods, but none of them call the private API, so there is no risk of being rejected by Apple.

Statement two:

The volume in the iOS device is divided into headphone volume and phone volume, which are independent of each other: but whether the headset or the phone is called a way to change the volume, change the headset volume when there is a headset on the device, and change the volume of the phone without the headset.

There is an open source project in GitHub: Systemvolumenativeextension. (Click to get Link)

Find SYSTEMVOLUMENATIVEEXTENSION/IOSVOLUMELIB/IOSVOLUMELIB/IOSVOLUMELIB.M this file after decompression.

Don't look too much, just pay attention to:

Float GetVolumeLevel () {    Mpvolumeview *slide = [Mpvolumeview new];    UISlider *volumeviewslider;        For (UIView *view in [slide subviews]) {if ([[[[[        View class] description] isequaltostring:@ "Mpvolumeslider"])        {            Volumeviewslider = (UISlider *) view;        }    }        float val = [Volumeviewslider value];    [Slide release];        return Val;}


&

Freobject SetVolume (Frecontext ctx, void* funcdata, uint32_t argc, Freobject argv[]) {    double newvolume;    Fregetobjectasdouble (Argv[0], &newvolume);        [[Mpmusicplayercontroller Applicationmusicplayer] setvolume:newvolume];        return NULL;}


If you think it's a little cumbersome: you can use it directly:

[[Mpmusicplayercontroller Applicationmusicplayer] setvolume:newvolume];

The range of Newvolume is 0 ~ 1;

Simply put, use this to set the headphone volume.

iOS programming to modify system volume

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.