iPhone播放音乐

来源:http://blog.csdn.net/htttw/article/details/7842295

iPhone播放音乐



今天我们简要介绍如何在iPhone中播放音乐:

强烈建议你参考官方文档(需要登录):

http://developer.apple.com/library/ios/#documentation/AVFoundation/Reference/AVAudioPlayerClassReference/Reference/Reference.html%23//apple_ref/doc/uid/TP40008067



1.

打开XCode,新建一个Window-based Application,项目名称是MusicPlayer:







2.

打开MainWindow.xib,按下图加入控件:



其中,最上面是两个Label,左边的Current(sec)始终不变,右边的0显示当前已播放的时间,下面是一个Slider,类似与一般播放器的进度条,再下面是音量调节的Slider,它们的min都是0.0,max都是1.0。最底下是两个Button。




3.

由于播放声音需要用到AVFoundation.framework,因此我们将它加入到我们的工程中:



右击Frameworks,选择Add/Existing Frameworks,加入AVFoundation:





4.

打开MusicPlayerAppDelegate.h,修改如下:

  1. //  
  2. //  MusicPlayerAppDelegate.h  
  3. //  MusicPlayer  
  4. //  
  5. //  Created by HuTao on 8/8/12.  
  6. //  Copyright __MyCompanyName__ 2012. All rights reserved.  
  7. //  
  8.   
  9. #import <UIKit/UIKit.h>  
  10. #import <AVFoundation/AVFoundation.h>  
  11.   
  12. @interface MusicPlayerAppDelegate : NSObject <UIApplicationDelegate>  
  13. {  
  14.     UIWindow * window;  
  15.       
  16.     IBOutlet UIButton * btnPlay;  
  17.     IBOutlet UILabel * labelVolume;  
  18.     IBOutlet UILabel * labelCurrentTime;  
  19.     IBOutlet UISlider * sliderCurrentTime;  
  20.       
  21.     NSTimer * playTimer;  
  22.       
  23.     AVAudioPlayer * player;  
  24. }  
  25.   
  26.   
  27. @property (nonatomic, retain) IBOutlet UIWindow * window;  
  28. @property (nonatomic, retain) IBOutlet UIButton * btnPlay;  
  29. @property (nonatomic, retain) IBOutlet UILabel * labelVolume;  
  30. @property (nonatomic, retain) IBOutlet UILabel * labelCurrentTime;  
  31. @property (nonatomic, retain) IBOutlet UISlider * sliderCurrentTime;  
  32.   
  33.   
  34. -(IBAction)soundStartOrPause:(id)sender;  
  35. -(IBAction)soundStop:(id)sender;  
  36. -(IBAction)volumeChanged:(id)sender;  
  37. -(IBAction)currentTimeChanged:(id)sender;  
  38.   
  39. -(void)updateSoundAt:(float)percent;  
  40. -(void)updateCurrentTime;  
  41. -(void)initPlayer;  
  42.   
  43.   
  44. @end  



首先,加入:

  1. #import <AVFoundation/AVFoundation.h>  

其次:

btnLabel,labelVolume,labelCurrentTime,sliderCurrentTime都是控件对应的Outlet:

btnLabel:在点击了Start按钮后文本需要变成Pause,所以我们给Button也增加了一个Outlet;

labelVolume,labelCurrentTime:在滑动Slider时对应的Label也需要变化以反应当前值;

sliderCurrentTime:歌曲播放时需要通过Slider来反应当前已播放的时间,因此Slider也需要一个Outlet。


之后的playerTimer会每一定时间运行一次,根据当前已播放的时间更新进度条;AVAudioPlayer是AVFoundation提供的播放音乐的一个类。


之后的四个IBAction分别是:按下Start按钮;按下Stop按钮;滑动音量的Slider;滑动已播放时间的Slider对应的Action。




5.

打开MusicPlayerAppDelegate.m,修改如下:

  1. //  
  2. //  MusicPlayerAppDelegate.m  
  3. //  MusicPlayer  
  4. //  
  5. //  Created by HuTao on 8/8/12.  
  6. //  Copyright __MyCompanyName__ 2012. All rights reserved.  
  7. //  
  8.   
  9. #import "MusicPlayerAppDelegate.h"  
  10.   
  11. @implementation MusicPlayerAppDelegate  
  12.   
  13. @synthesize window;  
  14. @synthesize btnPlay;  
  15. @synthesize labelVolume;  
  16. @synthesize labelCurrentTime;  
  17. @synthesize sliderCurrentTime;  
  18.   
  19.   
  20. #pragma mark -  
  21. #pragma mark Application lifecycle  
  22.   
  23.   
  24. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
  25. {  
  26.       
  27.     //初始化AVAudioPlayer  
  28.     [self initPlayer];  
  29.       
  30.     [window makeKeyAndVisible];  
  31.       
  32.     return YES;  
  33. }  
  34.   
  35.   
  36. -(void)initPlayer  
  37. {  
  38.     NSString * path = [[NSBundle mainBundle] pathForResource:@"北京欢迎你" ofType:@"mp3"];  
  39.       
  40.     //判断是否找到该音乐文件    
  41.     if (path)  
  42.     {  
  43.         NSLog(@"Init sound");  
  44.           
  45.         //用path路径初始化AVAudioPlayer  
  46.         player = [[AVAudioPlayer alloc]initWithContentsOfURL:[[NSURL alloc]initFileURLWithPath:path]error:nil];  
  47.           
  48.         //初始化播放器    
  49.         [player prepareToPlay];    
  50.           
  51.         //设置播放循环次数:如果numberOfLoops为负数 音频文件就会一直循环播放下去    
  52.         player.numberOfLoops = -1;    
  53.           
  54.         //设置音频音量:volume的取值范围在[0.0f, 0.1f]之间    
  55.         player.volume = 0.5f;  
  56.           
  57.         //将当前播放进度调为0  
  58.         [self updateSoundAt:0.0f];  
  59.     }  
  60. }  
  61.   
  62.   
  63. -(void)updateSoundAt:(float)percent  
  64. {  
  65.     float atTime = (player ? player.duration * percent : 0.0f);  
  66.       
  67.     NSString * time = [NSString stringWithFormat:@"%d", (int)atTime];  
  68.     labelCurrentTime.text = time;  
  69.       
  70.     sliderCurrentTime.value = percent;  
  71. }  
  72.   
  73.   
  74. -(IBAction)soundStartOrPause:(id)sender  
  75. {  
  76.     //点击Start按钮后开始播放音乐    
  77.     if(player)     
  78.     {  
  79.         UIButton * btn = (UIButton *)sender;  
  80.           
  81.         if(![player isPlaying])     
  82.         {  
  83.             NSLog(@"Start sound");  
  84.               
  85.             [player play];  
  86.             [btn setTitle:@"Pause" forState:UIControlStateNormal];  
  87.             if(!playTimer)  
  88.             {  
  89.                 playTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateCurrentTime) userInfo:nil repeats:YES];  
  90.             }  
  91.         }  
  92.         else  
  93.         {  
  94.             NSLog(@"Pause sound");  
  95.               
  96.             [player pause];  
  97.             [btn setTitle:@"Start" forState:UIControlStateNormal];  
  98.         }  
  99.     }    
  100. }  
  101.   
  102.   
  103. -(void)updateCurrentTime  
  104. {  
  105.     [self updateSoundAt:1.0 * player.currentTime / player.duration];  
  106. }  
  107.   
  108.   
  109.   
  110. -(IBAction)soundStop:(id)sender  
  111. {  
  112.     //停止播放声音    
  113.     if(player)  
  114.     {  
  115.         NSLog(@"Stop sound");  
  116.   
  117.         player.currentTime = 0;  
  118.         [player stop];  
  119.           
  120.         [btnPlay setTitle:@"Start" forState:UIControlStateNormal];  
  121.         [self updateSoundAt:0.0f];  
  122.     }  
  123. }    
  124.   
  125.   
  126.   
  127. -(IBAction)volumeChanged:(id)sender  
  128. {  
  129.     UISlider * slider = (UISlider *)sender;  
  130.     NSString * value = [[NSString alloc]initWithFormat:@"%d%%", (int)(slider.value * 100)];  
  131.     labelVolume.text = value;  
  132.     player.volume = slider.value;  
  133.     [value release];  
  134. }  
  135.   
  136.   
  137.   
  138. -(IBAction)currentTimeChanged:(id)sender  
  139. {  
  140.     UISlider * slider = (UISlider *)sender;  
  141.       
  142.     int time = (player ? slider.value * player.duration : 0);  
  143.       
  144.     player.currentTime = time;  
  145.       
  146.     [self updateSoundAt:slider.value];  
  147. }  
  148.   
  149.   
  150. - (void)dealloc  
  151. {  
  152.     [window release];  
  153.     [btnPlay release];  
  154.     [labelVolume release];  
  155.     [labelCurrentTime release];  
  156.     [sliderCurrentTime release];  
  157.       
  158.     [super dealloc];  
  159. }  
  160.   
  161.   
  162. @end  



有几点说明:

1.先将要播放的音乐加入到Resouces中;

2. playTimer定时器每0.5秒运行一次,更新当前的进度条;




6.

下面要开始将控件和IBOutlet以及IBAction相连接了:

(a)

打开MainWindow.xib,按住Ctrl键,鼠标从Music Player Delegate上拖动到相应的Label上,将它和IBOutlet相连接:


  要注意的是不要忘了连接btnStart!一共要连两个Slider,两个Label和一个Button。



(b)

右键Button,选择Touch Up Inside,将后面的小圆圈拖动到Music Player Delegate上,连接相应的IBAction:




要注意的是Slider需要连接ValueChanged事件:






7.

运行结果如下:





最后我把代码也上传上来了:

http://download.csdn.net/detail/htttw/4484442





完成!

原文地址:https://www.cnblogs.com/heyonggang/p/3498355.html