我有以下代码:
·H
#import <UIKit/UIKit.h>
-(id) initWithFrame: (CGRect)frame andPosition: (NSInteger)pos andValue: (NSInteger)value {
self = [super initWithFrame: frame];
if (self) {
self.frontImage = [UIImage imageNamed:[NSString stringWithFormat: @"front%ld.png", (long) (value+1)]];
self.backImage = [UIImage imageNamed:@"back"];
}
return self;
}
@end
好的,看起来很容易。只是一个带图像的框架。图像获得+1值。 但我无法弄明白如何使用声音文件。我想“链接”图像和相关的声音文件。文件有数字,例如front1,front2 ......和无声有sound1,sound2 ......
感谢您的帮助!
编辑:类似
self.audioplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:@"sfx%ld.wav", (long) (value+1)] error:NULL];
不起作用
答案 0 :(得分:0)
pathForResource
方法采用简单的NSString,而不是格式。这样做:
NSString *name = [NSString stringWithFormat:@"sfx%ld.wav", (long) (value+1)];
NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:nil];
NSURL *url = [[NSURL alloc] initFileURLWithPath:path];
self.audioplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
答案 1 :(得分:0)
尝试以下
NSString * strName = [NSString stringWithFormat:@"sfx%ld", (long) (value+1)];
NSString * strPath = [[NSBundle mainBundle] pathForResource:strName ofType:@"wav"];
NSURL * urlPath = [NSURL fileURLWithPath:strPath];
self.audioplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:urlPath error:NULL];
答案 2 :(得分:0)
-(id) initWithFrame: (CGRect)frame andPosition: (NSInteger)pos andValue: (NSInteger)value {
self = [super initWithFrame: frame];
if (self) {
self.frontImage = [UIImage imageNamed:[NSString stringWithFormat: @"card-%ld.png", (long) (value+1)]];
NSString * strName = [NSString stringWithFormat:@"sfx%ld", (long) (value+1)];
NSString * strPath = [[NSBundle mainBundle] pathForResource:strName ofType:@"wav"];
NSURL * urlPath = [NSURL fileURLWithPath:strPath];
self.audioplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:urlPath error:NULL];
[self.audioplayer play];
}
return self;
}
我想我必须说点按钮或其他东西?或音频播放器是否从initwithframe继承?