IOS使用AVAudioPlayer播放音乐文件

AVAudioPlayer 提供了大量的特性,包括暂停播放,调整音量,监控音频的峰值和均值等等。

AVAudioPlayer  *player;
NSString       *path;
 
// 设置音乐文件路径
path = [[NSBundle mainBundle] pathForResource:@"sound-file" ofType:@"mp3"];
 
// 判断是否可以访问这个文件
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) 
{    
  // 设置 player
  player = [[AVAudioPlayer alloc] initWithContentsOfURL:
     [NSURL fileURLWithPath:path] error:&error];
 
  // 调节音量 (范围从0到1)
  player.volume = 0.4f;
 
  // 准备buffer,减少播放延时的时间      
  [player prepareToPlay];
 
  // 设置播放次数,0为播放一次,负数为循环播放
  [player setNumberOfLoops:0];
 
  [player play];    
 
}    
 
...
 
// 清理工作
if (player != nil)
{
  if (player.isPlaying == YES)
    [player stop];
  [player release];
}
原文地址:https://www.cnblogs.com/tx8899/p/2545164.html