Wednesday, June 5, 2013

AVAudioPlayer enableRate example in Objective C (iOS).


AVAudioPlayer enableRate

A Boolean value that specifies whether playback rate adjustment is enabled for an audio player.

@property BOOL enableRate

Discussion of [AVAudioPlayer enableRate]
To enable adjustable playback rate for an audio player, set this property to YES after you initialize the player and before you call the prepareToPlay instance method for the player.

AVAudioPlayer enableRate example.
_noticeAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Rooster-mono" ofType:@"wav"]]
                                                      error:nil];;
if ([_noticeAudio respondsToSelector:@selector(setEnableRate:)])
    _noticeAudio.enableRate = YES;
if ([_noticeAudio respondsToSelector:@selector(setRate:)])
    _noticeAudio.rate = 2.0;

Example of [AVAudioPlayer enableRate].
player = [[AVAudioPlayer alloc] initWithContentsOfURL:
                  [NSURL fileURLWithPath:path] error:&err];
        player.volume = 0.4f;
        player.enableRate=YES;
        [player prepareToPlay];
        [player setNumberOfLoops:0];
        player.rate=2.0f;
        [player play];

AVAudioPlayer enableRate example.
-(void) playSound:(NSString *)filename
           volume:(float)volume
           ofType:(NSString *)type
         subtitle:(NSString *)text
            speed:(float)speed
            loops:(NSInteger)loops
{
    //playSound
    NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:type];
    theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path]
                                                                             error:nil];
    theAudio.delegate = self;
    theAudio.volume=volume;
    theAudio.enableRate=YES;
    theAudio.rate=speed;
    theAudio.numberOfLoops=loops;
    [theAudio prepareToPlay];
    [theAudio play];

    //display alert
    if (text!=nil) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                        message:text
                                                       delegate:self 
                                              cancelButtonTitle:@"Close"
                                              otherButtonTitles:nil];
        currentAlert=alert;
        [currentAlert show];
        duration= theAudio.duration/speed;
        [NSTimer    scheduledTimerWithTimeInterval:duration  
                                            target:self 
                                          selector:@selector(dismissAlert)   
                                          userInfo:nil
                                           repeats:NO];
        [alert release];
    }

}

End of AVAudioPlayer enableRate example article.