2013-04-25 263 views
0

任何人都可以指導我的教程,或演示我播放背景音樂的實際代碼。我需要它能夠開始和停止。這不是一個任務,所以你知道。我的任務已經完成,我只是想添加音樂,我不知道如何。謝謝!iPhone背景音樂播放器

回答

2

您可以使用AVAudioPlayer

//You have to import AvFoundation to use AVAudioPlayer 
#import <AVFoundation/AVFoundation.h> 

-(void) playMusicFile:(NSString *) songName 
{ 
    NSString *musicFile = [[NSBundle mainBundle] pathForResource:songName ofType:@"mp3"]; 

    NSError *soundError = nil; 
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:musicFile] error:&soundError]; 
    if(self.audioPlayer == nil) 
    { 
     NSLog(@"%@",soundError); 
    } 
    else 
    { 
     //Delegation is optional but it helps you do stuff after song finished playing etc 
     [self.audioPlayer setDelegate:self]; 
     //Set number of repeats, 0 is default plays once, negative values makes it play infinitely 
     [self.audioPlayer setNumberOfLoops:0]; 
     //Prepare to play is not always necessary, but otherwise it can take time to play 
     [self.audioPlayer prepareToPlay]; 
     [self.audioPlayer play]; 
    } 
} 

//This is the delegate called after the song finished playing, you can use it to play other songs, or do other stuff 
-(void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag 
{ 
    ... 
} 

停止和暫停:

//You can easily stop and pause using: 
[self.audioPlayer stop]; //Stop doesn't work as you would expect. It doesn't set the current time to 0 but only undoes the setup you had with the audioplayer. 
[self.audioPlayer pause]; 

//It is possible to call [self.audioPlayer play] after each method and playback will continue from where it left off. 

欲瞭解更多信息請訪問參考:http://developer.apple.com/library/ios/#DOCUMENTATION/AVFoundation/Reference/AVAudioPlayerClassReference/Reference/Reference.html

+0

真棒,謝謝一堆。我看到你的文件類型是@「mp3」,但是我應該在哪裏放置我喜歡的歌曲的實際名稱@「背景音樂」? – 2013-04-25 20:14:47

+0

我已經共享了一個函數playMusicFile,如果你想播放backgroundmusic.mp3就像這樣調用它:[self playMusicFile:@「backgroundmusic」]。 – guenis 2013-04-25 20:16:34

1

AVPlayerAVAudioPlayer應該工作。