[英]iPhone background music player
任何人都可以將我引導到教程中,或者向我顯示實際的代碼來播放背景音樂。 我需要它能夠啟動和停止。 這不是一項任務,所以您知道。 我的作業已經完成,我只想向其中添加音樂,但我不知道如何做。 謝謝!
您可以使用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
AVPlayer
和AVAudioPlayer
應該可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.