{
[super viewDidLoad];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//1.音频文件的url路径
NSURL *url=[[NSBundle mainBundle]URLForResource:@"235319.mp3" withExtension:Nil];
//2.创建播放器(注意:一个AVAudioPlayer只能播放一个url)
AVAudioPlayer *audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:Nil];
//3.缓冲
[audioPlayer prepareToPlay];
//4.播放
[audioPlayer play];
}
@end
代码说明:运行程序,点击模拟器界面,却并没有能够播放音频文件,原因是代码中创建的AVAudioPlayer播放器是一个局部变量,应该调整为全局属性。
可将代码调整如下,即可播放音频:
复制代码#import "YYViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface YYViewController ()
@property(nonatomic,strong)AVAudioPlayer *audioplayer;
@end
复制代码
@implementation YYViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//1.音频文件的url路径
NSURL *url=[[NSBundle mainBundle]URLForResource:@"235319.mp3" withExtension:Nil];
//2.创建播放器(注意:一个AVAudioPlayer只能播放一个url)
self.audioplayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:Nil];
//3.缓冲
[self.audioplayer prepareToPlay];
//4.播放
[self.audioplayer play];
}
@end
注意:一个AVAudioPlayer只能播放一个url,如果想要播放多个文件,那么就得创建多个播放器。










