2011-03-08 116 views
2

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

+2

@Federico谢谢你的见解。 :-) – 2011-03-08 19:21:15

+1

从现在起称我为Captain Obvious。我希望这很明显,我在开玩笑:-) – 2011-03-08 20:00:46

+0

@Federico(或者应该是@Captain?)是的,我会说这很明显,你是在开玩笑。 :-) – 2011-03-08 20:03:07

回答

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

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

最后,您需要将AVFoundation库添加到您的项目中。为此,请在Xcode的Groups & Files列中单击您的项目目标,然后选择“Get Info”。然后选择常规选项卡,单击底部“链接库”窗格中的+并选择“AVFoundation.framework”。

+0

这仍然适用于弧? – 2015-09-28 08:37:18

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

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

希望这会有所帮助。

干杯。

+0

我得到错误:“使用未声明的标识符'AVAudioPlayer'” – Linuxmint 2011-03-08 19:12:08

+1

请确保您的文件顶部或头文件中有#import 。 – 2011-03-08 19:13:41

+0

@Brenton不是在'#import '中吗? (很可能在两个,我想。) – 2011-03-08 19:15:48

相关问题