我想让一个应用程序播放由选择器选择的声音。
当我通过选择器选择文件时,如果我触摸按钮,则会播放声音。
但是,它不能。
我无法指出代码的错过。
任何人都可以帮我解决我的代码问题吗?
以下是我的问题排查代码。
.H文件
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface ViewController : UIViewController <
UIPickerViewDelegate,UIPickerViewDataSource,AVAudioPlayerDelegate> {
NSArray *ap;
NSString *si;
UIButton * utab;
AVAudioPlayer *apr;
}
@property (weak, nonatomic) IBOutlet UILabel *ll;
@property (weak, nonatomic) IBOutlet UIImageView *igv;
@property (weak, nonatomic) IBOutlet UIPickerView *pv;
@property (weak, nonatomic) NSArray *msa;
@end
.M文件
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
@property AVAudioPlayer *apr;
@end
@implementation ViewController
@synthesize ll,igv,pv;
- (void)viewDidLoad
{
[pv setDelegate:self];
[pv setDataSource:self];
[ll setText:[ap objectAtIndex:0]];
ap = [NSArray arrayWithObjects:@"AAA",@"BBB",@"CCC",@"DDD",@"EEE", nil];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@.m4a",[[NSBundle mainBundle] resourcePath]]];
NSError *error;
self.apr = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
apr.numberOfLoops = 2;
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return [ap count];
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent: (NSInteger)component {
return [ap objectAtIndex:row];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent: (NSInteger)component {
si = [ap objectAtIndex:row];
[ll setText:si];
NSString *in = [NSString stringWithFormat:@"%@.jpg",si];
UIImage *tig = [UIImage imageNamed:in ];
[igv setImage:tig];
}
- (IBAction)utabu {
[self.apr play];
}
@end
答案 0 :(得分:0)
很可能无法加载声音文件。初始化AVAudioPlayer后应检查错误变量。
创建URL对象的代码也是错误的。你应该使用:
[[NSBundle mainBundle] URLForRessource:<filename> withExtension:"m4a"]
每次选择声音文件时,您都必须创建一个新的AudioPlayer。
下次请使用更好的变量名,而不只是两三个字母垃圾。