AVAudioPlayerで再生速度を変化させる方法。AVAudioPlayerのインスタンスは、メソッド実行後も生存し続けなければならないのでクラス変数にしておく。再生速度(rate)は0.5から2.0の範囲で指定できる。enableRateをYESに設定し、rateを変化させると音程は一定で、再生速度だけが変化する。サンプルで使っているサウンドファイルは効果音源様から拝借させて頂きました。
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface WebViewController : UIViewController{
double rate;
AVAudioPlayer * player;
}
-(IBAction)play;
-(IBAction)speedChanged;
@property (nonatomic, retain) IBOutlet UIButton * button;
@property (nonatomic, retain) IBOutlet UISlider * slider;
@property (nonatomic, retain) IBOutlet UILabel * label;
@end
#import <AVFoundation/AVFoundation.h>
@interface WebViewController : UIViewController{
double rate;
AVAudioPlayer * player;
}
-(IBAction)play;
-(IBAction)speedChanged;
@property (nonatomic, retain) IBOutlet UIButton * button;
@property (nonatomic, retain) IBOutlet UISlider * slider;
@property (nonatomic, retain) IBOutlet UILabel * label;
@end
@implementation WebViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self speedChanged];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)speedChanged{
rate = powf(2,self.slider.value);
self.label.text = [NSString stringWithFormat:@"%0.3f", rate];
}
-(void)play{
NSString *path = [[NSBundle mainBundle] pathForResource:@"1839" ofType:@"mp3"];
NSURL * url = [NSURL fileURLWithPath:path];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
player.rate = rate;
player.enableRate = YES;
NSLog(@"%@", player);
[player play];
}
@end
- (void)viewDidLoad
{
[super viewDidLoad];
[self speedChanged];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)speedChanged{
rate = powf(2,self.slider.value);
self.label.text = [NSString stringWithFormat:@"%0.3f", rate];
}
-(void)play{
NSString *path = [[NSBundle mainBundle] pathForResource:@"1839" ofType:@"mp3"];
NSURL * url = [NSURL fileURLWithPath:path];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
player.rate = rate;
player.enableRate = YES;
NSLog(@"%@", player);
[player play];
}
@end