IOS audio Development

Source: Internet
Author: User

Audio knowledge is more complex than other programming methods. In particular, you must understand the specific parameters and methods used in the Framework. Otherwise, you may be confused when writing code.

1: Playing brief audio, such as button sound, can be achieved in this way.

I. Introduction framework:

#import <AudioToolbox/AudioToolbox.h>

2. Declare a sound source ID first

SystemSoundID _bookSoundID;

3. Provide the audio address to be played for sound source registration.

    NSURL *bookSoundUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"bookSound" ofType:@"wav"]];    AudioServicesCreateSystemSoundID((__bridge CFURLRef)bookSoundUrl, &_bookSoundID);

4. Play as needed:

AudioServicesPlaySystemSound(_bookSoundID);

5. Unused sound sources should be deleted

AudioServicesDisposeSystemSoundID(_bookSoundID);

2: AboutAvaudiosession usage

First knowAvaudiosessionIt is a singleton mode, that is, developers do not need to instantiate it themselves. This class plays a very important role in various audio environments.

I. First, SetAvaudiosessionType

Get input hardware get output hardware mixed with iPod follow the ring/mute button
AvaudiosessioncategoryambientNo Yes yes

AvaudiosessioncategorysoloambientNo Yes

AvaudiosessioncategoryplaybackNo Yes No

AvaudiosessioncategoryrecordYes No

AvaudiosessioncategoryplayandrecordYes No

Set a specific category based on actual usage. The setting code is as follows:

Avaudiosession * audiosession = [avaudiosession sharedinstance]; // obtain the avaudiosession singleton object [audiosession setdelegate: Self]; // set the proxy [audiosession setcategory: avaudiosessioncategoryplayandrecord error: & error]; // set the category, indicating that the app supports both playing and recording [audiosession setactive: Yes error: & error]; // start the audio session management, which blocks playing background music.

2. After recording or playing the audio, you can disable the audio session to continue playing the background music. The Code is as follows:

[[AVAudioSession sharedInstance] setActive:NO error: nil];

3. You can use audio sessions to forcibly set the application to use the specified output mode, such as the inner channel and speaker. The Code is as follows:

    UInt32 audioRouteOverride = hasHeadset ?kAudioSessionOverrideAudioRoute_None:kAudioSessionOverrideAudioRoute_Speaker;    AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride);

Kaudiosessionoverrideaudioroute_none

Kaudiosessionoverrideaudioroute_speaker speaker

4: How can I determine whether a user has inserted a headset? The Code is as follows: (reference: http://iandworld.sinaapp.com /? P = 184001)

-(Bool) hasheadset {// The simulator does not support # If target_iphone_simulator # warning *** simulator mode: audio session code works only on a device return no; # else cfstringref route; uint32 propertysize = sizeof (cfstringref); audiosessiongetproperty (response, & propertysize, & route); If (route = NULL) | (cfstringgetlength (route) = 0 )) {// silent mode nslog (@ "audioroute: silent, do nothing! ");} Else {nsstring * routestr = (_ bridge nsstring *) route; nslog (@" audioroute: % @ ", routestr);/* known values of route: * "headset" * "headphone" * "Speaker" * "speakerandmicrophone" * "comment" * "headsetinout" * "receiverandmicrophone" * "lineout" */nsange headphonerange = [routestr rangeofstring: @ "headphone"]; nsange headsetrange = [routestr rangeofstring: @ "headset"]; I F (headphonerange. location! = Nsnotfound) {return yes;} else if (headsetrange. location! = Nsnotfound) {return yes;} return no; # endif}

If yes is returned, the headset is inserted. If no is returned, the headset is not inserted.

5. Listen to the user unplug and insert the headset.

1: Register listener events and callback Functions

AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange,                                     audioRouteChangeListenerCallback,                                     self);

2. Implement the callback function for related processing:

void audioRouteChangeListenerCallback (                                       void                      *inUserData,                                       AudioSessionPropertyID    inPropertyID,                                       UInt32                    inPropertyValueSize,                                       const void                *inPropertyValue                                       ) {    if (inPropertyID != kAudioSessionProperty_AudioRouteChange) return;    // Determines the reason for the route change, to ensure that it is not    //because of a category change.    CFDictionaryRefrouteChangeDictionary = inPropertyValue;    CFNumberRef routeChangeReasonRef =    CFDictionaryGetValue (routeChangeDictionary,                          CFSTR (kAudioSession_AudioRouteChangeKey_Reason));    SInt32 routeChangeReason;    CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);    NSLog(@" ===================================== RouteChangeReason : %d", routeChangeReason);    AudioHelper *_self = (AudioHelper *) inUserData;    if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable) {        [_self resetSettings];        if (![_self hasHeadset]) {            [[NSNotificationCenter defaultCenter] postNotificationName:@"ununpluggingHeadse"                                                                object:nil];        }    } else if (routeChangeReason == kAudioSessionRouteChangeReason_NewDeviceAvailable) {        [_self resetSettings];        if (![_self hasMicphone]) {            [[NSNotificationCenter defaultCenter] postNotificationName:@"pluggInMicrophone"                                                                object:nil];        }    } else if (routeChangeReason == kAudioSessionRouteChangeReason_NoSuitableRouteForCategory) {        [_self resetSettings];        [[NSNotificationCenter defaultCenter] postNotificationName:@"lostMicroPhone"                                                            object:nil];    }    //else if (routeChangeReason == kAudioSessionRouteChangeReason_CategoryChange  ) {    //    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];    //}    [_self printCurrentCategory];}

6. How can I keep the background music playing? (Reference: http://blog.csdn.net/yhawaii/article/details/7788340)


1: In info. plist, add"Required background Modes"Key, and its value settings are shown in:

2: The system Audio Service supports audio playback and disables other audio that are being played.

AVAudioSession *session = [AVAudioSession sharedInstance];[session setActive:YES error:nil];[session setCategory:AVAudioSessionCategoryPlayback error:nil];

3: Set the app to support remote control Event code:

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

Set the app to support remote control events. In fact, the app icon is displayed in the dock. When you click the image, open the app, as shown in:

4: RunAvaudioplayer

7. Volume

1: The application automatically obtains the system volume.

UInt32 dataSize = sizeof(float);AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareOutputVolume,                                           &dataSize,                                           &keyVolume);

Make sure that

AVAudioSession *session = [AVAudioSession sharedInstance];[session setActive:YES error:nil];[session setCategory:AVAudioSessionCategoryPlayback error:nil];

2: automatically set the system volume by the application (reference: http://blog.csdn.net/studyrecord/article/details/6452354)

8. Implementation of audio downloading and Playback.

See audiostreamer

Https://github.com/mattgallagher/AudioStreamer

If you just want to play the video online, do not process it. it is also possible to use avplayer and so on to achieve online playback. But if you want to achieve more and better, don't let it go and waste your life.

Related Article

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.