ios播放音乐
库中添加AVFoundation.framework
#import
<AVFoundation/AVFoundation.h>
@interface tanzoe_ViewController :
UIViewController<AVAudioPlayerDelegate>
//添加协议<AVAudioPlayerDelegate>
{
AVAudioPlayer *mp3;//定义对象
}
NSString *questionSoundName = @"pao_bg";
NSString *currentSoundFilePath = [[NSBundle mainBundle]
pathForResource:questionSoundName ofType:@"mp3"];
NSURL *currentFileURL = [NSURL
fileURLWithPath:currentSoundFilePath];
self.mp3 = [[[AVAudioPlayer alloc]
initWithContentsOfURL:currentFileURL error:nil] autorelease];
self.mp3.numberOfLoops = 1;//播放次数 0为1次 1为两次
self.mp3.volume = 0.3;//播放音量
[self.mp3 play];//播放音乐
[self.mp3 stop];//播放暂停
[self.mp3 pause];//播放暂停
[self.mp3 play];//播放继续
if([carInBox
isPlaying])
{
[carInBox pause];//如果正在播放歌曲 先暂停
carInBox.currentTime = 0.0f;//然后将播放进度退回到0秒,
[carInBox play];//重新播放
}
else
{
[carInBox play];
}
if([self.mp3 prepareToPlay]==YES)//准备播放
{
[self.mp3 play];
}
[self.mp3 setDelegate:self];//设置代理
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player
successfully:(BOOL)flag
{
NSLog(@"finish");//设置代理的AVAudioPlayer对象每次播放结束都会触发这个函数
}