什么是播放循环声音最简单的方法?

时间:2011-03-08 18:52:33

标签: iphone objective-c

在iPhone应用中播放循环声音的最简单方法是什么?

2 个答案:

答案 0 :(得分:15)

最简单的解决方案可能是使用AVAudioPlayer并将numberOfLoops:设置为负整数。

// *** In your interface... ***
#import <AVFoundation/AVFoundation.h>

...

AVAudioPlayer *testAudioPlayer;

// *** Implementation... ***

// Load the audio data
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"sample_name" ofType:@"wav"];
NSData *sampleData = [[NSData alloc] initWithContentsOfFile:soundFilePath];
NSError *audioError = nil;

// Set up the audio player
testAudioPlayer = [[AVAudioPlayer alloc] initWithData:sampleData error:&audioError];
[sampleData release];

if(audioError != nil) {
    NSLog(@"An audio error occurred: \"%@\"", audioError);
}
else {
    [testAudioPlayer setNumberOfLoops: -1];
    [testAudioPlayer play];
}



// *** In your dealloc... ***
[testAudioPlayer release];

您还应该记住设置适当的音频类别。 (请参阅AVAudioSession setCategory:error:方法。)

最后,您需要将AVFoundation库添加到项目中。要执行此操作,请在“组”和“组”中单击项目的目标。 Xcode中的Files列,然后选择“获取信息”。然后选择常规选项卡,单击底部“链接库”窗格中的+,然后选择“AVFoundation.framework”。

答案 1 :(得分:6)

最简单的方法是将AVAudioPlayer设置为无限数量的循环(如果需要,则为有限循环)。

类似的东西:

NSString *path = [[NSBundle mainBundle] pathForResource:@"yourAudioFileName" ofType:@"mp3"];
NSURL *file = [[NSURL alloc] initFileURLWithPath:path];

AVAudioPlayer *_player = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:nil];
[file release];

_player.numberOfLoops = -1; 
[_player prepareToPlay];
[_player play]; 

这将简单地循环您无限期指定的任何音频文件。 如果您希望音频文件循环次数有限,请将循环次数设置为任何正整数。

希望这有帮助。

干杯。

相关问题