IOS development intermediate: audio uses avaudioplayer to implement systemsoundservice

Source: Internet
Author: User

In previous blog posts, we have explained avaudioplayer and systemsoundservice usage. These two functions are suitable for playing game sound effects to a certain extent. Both have their own advantages and disadvantages. Which of the following are summarized:

1) Advantages of avaudioplayer

(1) You can play music of any length;

(2) loop playback;

(3) You can control the playback time;

(4) The sound volume can be controlled to achieve the stereo effect;

(5) You can adjust the volume.

2) avaudioplayer disadvantages

(1) The player must be loaded before playback, and cannot be played immediately;

(2) One audioplayer can only play the loaded music at a time, and cannot play the same music several times at a time.

(3) No vibration effect

3) Advantages of systemsoundservice:

(1) instant playback

(2) ability to play music multiple times at the same time

(3) vibration effects can be added.

4) Disadvantages of systemsoundservice:

(1) loop playback is not allowed.

(2) The playback time cannot be controlled.

(3) channels cannot be controlled

(4) volume cannot be controlled

(5) The Music cannot be paused.


We found that the advantages and disadvantages of the two music playing modes are almost completely complementary. So what is the purpose?

Key: Here we are considering playing the game sound! All of them are short-term Audio Playback!

Imagine a game. Sometimes we have to play a sound effect repeatedly. Sometimes we want a vibration. Sometimes we need to play the same audio multiple times in a short time!

Therefore, we can consider combining the two features!

Method:

Use avaudioplayer to implement systemsoundservice! Avaudioplayer disadvantage


First, let's clarify the functions we need:

(1) You can play the video immediately after initialization.

(2) The same audio can be played multiple times within a period of time. Here is a detailed description: When avaudioplayer is used, it must be stopped after play to play again. What we need to improve here is that even if the previous playback is not over, we can start a new playback, which is especially suitable for playing the percussion sound, in this way, we will feel the sound of multiple beats, rather than just one. Remember, this is not a mix of avaudioplayer.

(3) loop playback

(4) pause and stop playing

(5) able to play vibration and play audio and vibrate

(6) channels can be adjusted

(7) adjustable volume


Next we will create a new custom class.

The following is the header file code:

# Import <avfoundation/avfoundation. h> # import <audiotoolbox/audiotoolbox. h> @ interface sraudioplayer: nsobject {avaudioplayer * _ audioplayer1; avaudioplayer * _ audioplayer2;} @ property (nonatomic, assign) float pan; // adjust the channel balance @ property (nonatomic, assign) float volume; // adjust the volume // initialize-(ID) initwithcontentsofurl :( nsurl *) URL error :( nserror * _ autoreleasing *) outerror; // play once-(void) playonce; // loop-(void) playinfinite; // play and vibrate-(void) playoncewithvibrate;-(void) pause; -(void) Stop; // vibration-(void) vibrate; @ end

Here we have two avaudioplayer instances to simulate playing the same audio multiple times in a period of time.


The following is the code of the M file:

#import "SRAudioPlayer.h"@implementation SRAudioPlayer{    BOOL _isPlayingAudioPlayer1;}- (id)initWithContentsOfURL:(NSURL *)URL error:(NSError *__autoreleasing *)outError{    if ((self = [super init])) {        _audioPlayer1 = [[AVAudioPlayer alloc] initWithContentsOfURL:URL error:outError];        _audioPlayer2 = [[AVAudioPlayer alloc] initWithContentsOfURL:URL error:outError];                [_audioPlayer1 prepareToPlay];        [_audioPlayer2 prepareToPlay];    }    return self;}- (void)setPan:(float)pan{    if (_pan != pan) {        _pan = pan;        _audioPlayer1.pan = pan;        _audioPlayer2.pan = pan;    }}- (void)setVolume:(float)volume{    if (_volume != volume) {        _volume = volume;        _audioPlayer1.volume = volume;        _audioPlayer2.volume = volume;    }}- (void)playOnce{    _audioPlayer1.numberOfLoops = 1;    if (!_isPlayingAudioPlayer1) {        if (!_audioPlayer1.isPlaying) [_audioPlayer1 play];        else _audioPlayer1.currentTime = 0.0f;        _isPlayingAudioPlayer1 = YES;    } else {        if (!_audioPlayer2.isPlaying)[_audioPlayer2 play];        else _audioPlayer2.currentTime = 0.0f;        _isPlayingAudioPlayer1 = NO;    }}- (void)playInfinite{    [_audioPlayer2 pause];    _audioPlayer1.currentTime = 0.0f;    _audioPlayer1.numberOfLoops = -1;  }- (void)playOnceWithVibrate  //1{    _audioPlayer1.numberOfLoops = 1;    if (!_isPlayingAudioPlayer1) {        if (!_audioPlayer1.isPlaying) [_audioPlayer1 play];        else _audioPlayer1.currentTime = 0.0f;        _isPlayingAudioPlayer1 = YES;    } else {        if (!_audioPlayer2.isPlaying)[_audioPlayer2 play];        else _audioPlayer2.currentTime = 0.0f;        _isPlayingAudioPlayer1 = NO;    }    [self vibrate];}- (void)pause{    [_audioPlayer1 pause];    [_audioPlayer2 pause];}- (void)stop{    [_audioPlayer1 stop];    [_audioPlayer2 stop];}- (void)vibrate{    AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);}@end

Here we mainly talk about the trick feature implementation:

We use two players. Here, if playonce is used, we can determine which player is currently playing. If Player 1 is used, we can use PLAYER 2 for playing. On the other hand, if both players are playing at the same time, we will pull the playing time to the head, which is the same as playing again. In this way, we will feel multiple audios when playing sound effects. Of course, if you want to simulate better, you need to get a few more avaudioplayers, but this will consume more resources.


Okay, let's talk about it! If you have any questions or find a bug in the program, you can send a comment!


[This article is an original article. If you need to forward it, please indicate the source: From songrotek's blog! Thank you for your cooperation.]

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.