2015-08-20 47 views
2

我對每個聲音包有11個聲音。它們被命名爲:聲音隨機化最簡單的方法是什麼

  • testpack1.mp3,
  • testpack2.mp3等。

我的球員,此代碼初始化它們:

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]; 

這聽起來會通過按下按鈕來播放。例如,我已經生成了4個按鈕,這4個按鈕每次只播放testpack1-4.mp3,但我希望我的播放器從11種聲音中隨機選取。什麼是最簡單的解決方案?

注:我不想重複播放MP3,除非所有播放

回答

2

這個怎麼樣?

int randNum = rand() % (11 - 1) + 1; 

的formuale就像下面

int randNum = rand() % (maxNumber - minNumber) + minNumber; 
+0

沒錯,和在代碼的發佈問題第一線,以從randNum此答案替換值+ 1。 – Bamsworld

+0

謝謝,但我忘了說,每個聲音應該只採取一次... – iOSBeginner

+0

@iOSBeginner:好的...創建一個已完成的數字數組,並檢查該數字是否已完成,再次調用randNum ..而已... –

-2

你有沒有嘗試過這樣的:

NSUInteger value = arc4random(11) + 1;

NSUInteger value = arc4random_uniform(11) + 1;(iOS版> 4.3)

這會給你一個介於0和10之間的隨機數,然後加1.因此你的文件將從yourString1到yourString11。

2

一個建議:

它聲明3個變量爲靜態變量,played是一個簡單的C-陣列

static UInt32 numberOfSounds = 11; 
static UInt32 counter = 0; 
static UInt32 played[11]; 

如果計數器playSound()將C-Array對零個值的方法,0和將計數器設置爲聲音的數量。 當調用該方法時,隨機生成器會創建一個索引號。

  • 如果該索引在數組中的值爲0,則播放聲音,設置數組中的索引並減少計數器。
  • 如果該索引處的聲音已播放完畢,則循環播放直到找到未使用的索引。

    - (void)playSound 
    { 
        if (counter == 0) { 
        for (int i = 0; i < numberOfSounds; i++) { 
         played[i] = 0; 
        } 
        counter = numberOfSounds; 
        } 
        BOOL found = NO; 
        do { 
        UInt32 value = arc4random_uniform(numberOfSounds) + 1; 
        if (played[value - 1] != value) { 
         NSString * strName = [NSString stringWithFormat:@"testpack1-%d", value]; 
         NSString * strPath = [[NSBundle mainBundle] pathForResource:strName ofType:@"mp3"]; 
         NSURL * urlPath = [NSURL fileURLWithPath:strPath]; 
         self.audioplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:urlPath error:NULL]; 
         played[value - 1] = value; 
         counter--; 
         found = YES; 
        } 
        } while (found == NO); 
    } 
    
相關問題