Elton's Blog

使用AVAudioPlayer播放音乐文件

by on 十二.07, 2009, under iPhone

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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];
}




:,

25 Comments for this entry

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit my friends!

A few highly recommended friends...