使用AVAudioPlayer播放音乐文件

AVAudioPlayer 提供了大量的特性,包括暂停播放,调整音量,监控音频的峰值和均值等等。 我们看下面的例子:

  1.  
  2. AVAudioPlayer  *player;
  3. NSString       *path;
  4.  
  5. // 设置音乐文件路径
  6. path = [[NSBundle mainBundle] pathForResource:@"sound-file" ofType:@"mp3"];
  7.  
  8. // 判断是否可以访问这个文件
  9. if ([[NSFileManager defaultManager] fileExistsAtPath:path])
  10. {    
  11.   // 设置 player
  12.   player = [[AVAudioPlayer alloc] initWithContentsOfURL:
  13.      [NSURL fileURLWithPath:path] error:&error];
  14.  
  15.   // 调节音量 (范围从0到1)
  16.   player.volume = 0.4f;
  17.  
  18.   // 准备buffer,减少播放延时的时间      
  19.   [player prepareToPlay];
  20.  
  21.   // 设置播放次数,0为播放一次,负数为循环播放
  22.   [player setNumberOfLoops:0];
  23.  
  24.   [player play];    
  25.  
  26. }    
  27.  
  28.  
  29. // 清理工作
  30. if (player != nil)
  31. {
  32.   if (player.isPlaying == YES)
  33.     [player stop];
  34.   [player release];
  35. }
posted @ 2010-10-22 21:40  周宏伟  阅读(717)  评论(0编辑  收藏  举报