调用一次随机数组的声音并使用按钮播放它

问题描述:

我想随机化一个数组声音文件。调用一次随机数组的声音并使用按钮播放它

- (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

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