2011-03-08 184 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

相關問題