iphone播放音乐的2种方式

 

 

方法一:使用AudioToolbox

1.导入文件和加载framwork

 #import <AudioToolbox/AudioToolbox.h>

 加载AudioToolbox.framework

2.获取文件路径

 NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"mp3"];

3.播放声音

 if (path) { //播放声音

   SystemSoundID soundId;

   AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &soundId);

   AudioServicesPlaySystemSound(soundId);  

 }

 

方法二:使用AVAudioPlayer

1.倒入头文件和加载framwork

 #import <AVFoundation/AVFoundation.h>

 加载AVFoundation.framework

2.获取文件路径

 NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"mp3"];

3.定义AVAudioPlayer对象并初始化

 AVAudioPlayer *player;

 if(!player && path)

 {

   player = [[AVAudioPlayer alloc] initWithContentsOfURL:(NSURL*)[NSURL fileURLWithPath:path] error:nil];  

   [player prepareToPlay];

 }

4.播放声音

 if (player)

 {  

    [player play];      //播放

        //[player pause]; //暂停

   //[player stop];  //停止

   //更多强大功能......

 }

 

 

你可能感兴趣的:(iPhone)