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

Lin*_*int 2 iphone objective-c

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

Joh*_*ker 15

也许最简单的解决办法是使用一个AVAudioPlayernumberOfLoops:设置为一个负整数.

// *** 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];
Run Code Online (Sandbox Code Playgroud)

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

最后,您需要将AVFoundation库添加到项目中.为此,请在Xcode的"组和文件"列中单击项目的目标,然后选择"获取信息".然后选择General选项卡,单击底部"Linked Libraries"窗格中的+,然后选择"AVFoundation.framework".


Bre*_*rse 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]; 
Run Code Online (Sandbox Code Playgroud)

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

希望这可以帮助.

干杯.