在程序中实现插入音乐的代码及详解

来源:互联网 发布:注册域名免费 编辑:程序博客网 时间:2024/05/16 06:04

#import

#import


@interface AudioPlayerViewController :UIViewController<</span>AVAudioPlayerDelegate>

{


   //播放音频的控件

    AVAudioPlayer *audioPlayer;


}

@property(nonatomic,retain) AVAudioPlayer *audioPlayer;

@end





#import"AudioPlayerViewController.h"


@interfaceAudioPlayerViewController ()


@end


@implementationAudioPlayerViewController

@synthesize audioPlayer;

- (id)initWithNibName:(NSString *)nibNameOrNilbundle:(NSBundle*)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

       // Custominitialization

    }

   return self;

}

//视图资源的加载

-(void)loadView{

    

   //定义UIView

   UIView *view= [[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];

   view.backgroundColor =[UIColor orangeColor];

    self.view = view;

    

   //定义按钮

   UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    button.frame = CGRectMake(90, 100, 160, 40);

   [button setTitle:@"开始播放"forState:UIControlStateNormal];

   [button addTarget:selfaction:@selector(startPlayer) forControlEvents:UIControlEventTouchUpInside];

   //添加显示

    [self.view addSubview:button];

    

   //定义按钮

   UIButton *btn2= [UIButtonbuttonWithType:UIButtonTypeRoundedRect];

    btn2.frame = CGRectMake(90, 200, 160, 40);

   [btn2 setTitle:@"停止播放"forState:UIControlStateNormal];

   [btn2 addTarget:selfaction:@selector(stopPlayer) forControlEvents:UIControlEventTouchUpInside];

   //添加显示

    [self.view addSubview:btn2];

    

}


//添加震动

-(void)stopPlayer{

    

   [audioPlayer stop];

    

}


//播放声音

-(void)startPlayer{

   //定义URl

   NSURL*audioPath = [[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:@"wdgsl" ofType:@"mp3"]];

    

    NSError *error = nil;

    

   //播放器初始化操作

    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioPatherror:&error];

    

   //设置代理

   audioPlayer.delegate = self;

   //判断是否错误,如果错误应该直接return;

    if (error!=nil) {

       NSLog(@"播放遇到错误了信息:%@",[errordescription]);

       return ;

    }

   //开始播放

   [audioPlayer play];

}


//播放完成

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)player successfully:(BOOL)flag{

   NSLog(@"播放完成!!");

}


//播放解码错误

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer*)player error:(NSError*)error{


NSLog(@"解码错误!!");



}





- (void)dealloc

{

   [audioPlayer release];

    [super dealloc];

}


- (void)viewDidLoad

{

   [superviewDidLoad];

// Do any additional setup after loading the view.

}


- (void)didReceiveMemoryWarning

{

   [superdidReceiveMemoryWarning];

   // Dispose of any resources that can berecreated.

}


@end


原创粉丝点击