-2
嗨,我有一個應用程序,你必須按下一個按鈕後吹至手機併發出聲音,這裏是代碼:一站式音樂立即
#import "AirInstrumentViewController.h"
@implementation AirInstrumentViewController
@synthesize audiOfA;
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL fileURLWithPath:@"/dev/null"];
NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat: 44100.0], AVSampleRateKey,
[NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
[NSNumber numberWithInt: AVAudioQualityMax], AVEncoderAudioQualityKey,
nil];
NSError *error;
recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
if (recorder) {
[recorder prepareToRecord];
recorder.meteringEnabled = YES;
[recorder record];
levelTimer = [NSTimer scheduledTimerWithTimeInterval: 0.03 target: self selector: @selector(levelTimerCallback:) userInfo: nil repeats: YES];
} else
NSLog([error description]);
}
- (void)levelTimerCallback:(NSTimer *)timer {
[recorder updateMeters];
const double ALPHA = 0.05;
double peakPowerForChannel = pow(10, (0.05 * [recorder peakPowerForChannel:0]));
lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * lowPassResults;
if (lowPassResults > 0.55) {
NSLog(@"Mic blow detected");
if (aIsBeingTouched == YES) {
NSString *musicString = [[NSBundle mainBundle] pathForResource:@"A" ofType:@"aifc"];
audiOfA = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:musicString] error:NULL];
[audiOfA play];
} }else {
[audiOfA stop];
}
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
if (CGRectContainsPoint(aImage.frame, touchLocation)) {
aImage.image = [UIImage imageNamed:@"active.png"];
aIsBeingTouched = YES;
}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[audiOfA stop];
aImage.image = [UIImage imageNamed:@"a.png"];
aIsBeingTouched = NO;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
@end
我希望你明白我想去做。在此處: 如果(lowPassResults> 0.55){NSLog(@「Mic blow detected」);
if (aIsBeingTouched == YES) {
NSString *musicString = [[NSBundle mainBundle] pathForResource:@"A" ofType:@"aifc"];
audiOfA = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:musicString] error:NULL];
[audiOfA play];
} }else {
[audiOfA stop];
}
}
聲音持續時間更長,然後停止。相同的觸摸結束。如果我在拍下圖像的同時擊倒 ,那麼當我最終把圖像放下時,即使我沒有吹,因爲我在沒有按下時發出聲音,它可能會記錄下它或者有些東西!我不知道如何解決所有這些問題,請幫助!
我不明白,鏈接如何能夠幫助我 – user918958
實際的音樂停止像一秒鐘後,雖然 – user918958
因爲你可以使用'NSOperation'爲'AVAudio'節,這樣的過程是在一個單獨的線程中完成,並會因此加快了主線程,並提高了所有'NSTimer'以及觸摸事件和其他UI元素的時間。 – msgambel