2015-04-17 85 views
1

我想隨機化一個數組聲音文件。調用一次隨機數組的聲音並使用按鈕播放它

- (void)generateRandomizedSounds { 
    int randomSoundNumber = arc4random() % 4; //random number from 0 to 3 

    NSLog(@"random sound number = %i", randomSoundNumber); 

    NSString *effectTitle; 

    switch (randomSoundNumber) { 
     case 0: 
      effectTitle = @"bell"; 
      break; 
     case 1: 
      effectTitle = @"brake"; 
      break; 
     case 2: 
      effectTitle = @"dog"; 
      break; 
     case 3: 
      effectTitle = @"bird"; 
      break; 

     default: 
      break; 
    } 
    SystemSoundID soundID; 

    NSString *soundPath = [[NSBundle mainBundle] pathForResource:effectTitle ofType:@"mp3"]; 
    NSURL *soundUrl = [NSURL fileURLWithPath:soundPath]; 

    AudioServicesCreateSystemSoundID ((__bridge CFURLRef)soundUrl, &soundID); 
    AudioServicesPlaySystemSound(soundID); 

    return; 
} 

好吧,現在我想玩一個按鈕的每個案例。

但我試過的一切都出錯了錯誤。

+2

你試過了什麼?發生了什麼錯誤? – Martze

+0

我試着用[self.soundID play],並將SystemSoundID中的片段集成到按鈕中,但沒有任何效果。 – Sausagesalad

回答

0

AudioServicesPlaySystemSound()功能無法播放任何MP3文件。該功能僅支持以下文件格式:.caf.aac.wav,聲音必須爲30秒或更短。

你玩使用此功能必須

聲音文件: 不超過30秒的持續時間以線性PCM或IMA4(IMA/ADPCM)中的.caf,.AIF封裝格式,或者.wav文件

https://developer.apple.com/library/ios/documentation/AudioToolbox/Reference/SystemSoundServicesReference/index.html#//apple_ref/c/func/AudioServicesPlaySystemSound

因此,如果clock.mp3是在持續時間不到30秒,你可以播放聲音,如果轉換文件格式。

要使用afconvert命令轉換mp3caf,例如象下面這樣:

$ afconvert -f caff -d ima4 bell.mp3 bell.caf 

如果不是(聲音超過30秒),使用的AVFoundation.frameworkAVPlayer代替。

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"bell" ofType:@"mp3"]; 
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath]; 

AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil]; 
[player play];