为按钮随机化音频

时间:2015-08-20 21:54:48

标签: ios objective-c audio

每个soundpack我有9个声音。 它们的名称为:testpack1.mp3,testpack2.mp3等。 我也有多达9个按钮。有时候只有4个,有时候只有9个。

我生成我的按钮并使用以下代码初始化声音:

-(id) initWithFrame: (CGRect)frame andPosition: (NSInteger)pos andValue: (NSInteger)value {

NSString * strName = [NSString stringWithFormat:@"testpack%ld", (long) (value+1)];
NSString * strPath = [[NSBundle mainBundle] pathForResource:strName ofType:@"mp3"];
NSURL * urlPath = [NSURL fileURLWithPath:strPath];
self.audioplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:urlPath error:NULL];
}

我在VC中使用

调用此方法
Sounds *so = [[Sounds alloc] initWithFrame:frame andPosition:i andValue:value];
每个按钮

。 因此,价值每次都会增加1.

好的,现在按下生成的按钮即可播放声音。例如,我已经生成了4个按钮,这4个按钮每次只播放testpack1-4.mp3但是我希望我的播放器随机取出9个声音。

如果我只是说,arc4random,并改变

中的第一行
NSString * strName = [NSString stringWithFormat:@"testpack%ld", (long) (value+randomNumber)];

我有时会得到零,因为它超过了9。

如果我有所有9个按钮,所有声音都有一个特定的按钮。一切都好。我只有4或6个按钮,我的播放器总是只拍摄前4或6个声音,但9个声音中只有6个。

我希望我的问题是可以理解的,我不知道如何更好地解释我的问题......

1 个答案:

答案 0 :(得分:0)

使用

生成0到9之间的随机数
[class ReviewForm (forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ReviewForm, self).__init__(*args, **kwargs)
        self.fields\['location'\]=forms.CharField(widget=forms.TextInput(attrs={'id':'myField'}),label='', required=False)
        self.fields\['review'\]=forms.CharField(widget=forms.TextInput(attrs={'id':'myField'}),label='', required=False)

我认为在你的情况下,使用NSInteger randomNumber = arc4random() % 10; 并在创建字符串时添加一个字符串,使其永远不会为0或高于9