【转】AVAudioPlayer播放音乐,最清晰明了

简介:

在xcode中手动添加frameWork。

 

#import "MusicViewController.h"

#import <AVFoundation/AVFoundation.h>

#import <AudioToolbox/AudioToolbox.h>

  

@implementation MusicViewController

@synthesize start;

@synthesize pause;

@synthesize restart;

@synthesize BT1;

@synthesize player;

 

-(IBAction)tostart:(id)sender{

    [player play];   //播放

    AudioSessionSetActive (true); 

}

 

-(IBAction )topause:(id)sender{

    [self.player pause];

    AudioSessionSetActive (false);//要引入tool包才行,不然报错

}

 

 

- (void)dealloc

{

    [BT1 release];

    [super dealloc];

}

 

- (void)didReceiveMemoryWarning

{

    // Releases the view if it doesn't have a superview.

    [super didReceiveMemoryWarning];

    

    // Release any cached data, images, etc that aren't in use.

}

 

#pragma mark - View lifecycle

 

 

 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

 - (void)viewDidLoad

 {

     NSString * musicFilePath = [[NSBundle mainBundle] pathForResource:@"audio" ofType:@"mp3"];      //创建音乐文件路径    

     NSURL * musicURL= [[NSURL allocinitFileURLWithPath:musicFilePath];  

     

     AVAudioPlayer * thePlayer  = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:nil];

     //创建播放器

     self.player = thePlayer;    //赋值给自己定义的类变量

     

     [musicURL release];

     [thePlayer release];

     

     

     [player setVolume:1];   //设置音量大小0-1之间

     player.numberOfLoops = -1;//设置音乐播放次数  -1为一直循环

     

     [super viewDidLoad];

 }

 

 

- (void)viewDidUnload //内存警告时才会释放,当前的viewController即使出现内存警告,也不会unload

{

    [self setBT1:nil];

    [super viewDidUnload];

    // Release any retained subviews of the main view.

    // e.g. self.myOutlet = nil;

}

 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

{

    // Return YES for supported orientations

    return (interfaceOrientation == UIInterfaceOrientationPortrait);

}

 

@end

 

------------------------------------------------------------------

运行出来效果(这个就是你在IB里面以绑定事件就行)

AVAudioPlayer的用法 <wbr><wbr> <wbr><wbr>老穆奉献

 

PS:这里有几个问题需要说明以下

1. 这个[player play] 和【player pause】 时AVAudioPlayer自带的方法,默认情况下你暂停后,再play他会接着你刚才那个继续放,原因时这个play再这个view没有被dealloc之前 ,对象一直没有被销毁。

2.使用slider 当音控调教装置

代码很简单

 

-(IBAction) volumeChange:(id) sender{

    self.player.volume = volumebar.value;

}

 

/////////////////////////////////////////////

 iPhone应用轻松使用AVAudioPlayer音频播放是本文要介绍的内容,iPhone SDK中的AVFoundation框架包括的AVAudioPlayer是一个容易使用而且功能强大,基于Object-c的播放音频文件播放器  。本教程展示了怎样使用AVAudioPlayer  。本教程将建立一个简单的程序,它能够循环播放一段mp3音频文件  。

  源代码/Guithub

  教程的源代码在GitHub上  。你可以从仓库中克隆或直接下载zip文件  。

  创建项目

  1. Launch Xcode and create a new View-Based iPhone application called AudioPlayer: 

  启动Xcode并创建一个“View-Based iPhone application”项目,取名为AudioPlayer:

  1.从Xcode菜单选择“File > New Project …”

  2.从“iPhone OS > Application”部分选择“View-based Application”,然后按“Choose…”

  3.将项目命名为“AudioPlayer”并按“Save”
    
添加AVFoundation框架

  为使用SDK的AVAudioPlayer类,我们需要将AVFoundation框架加入项目:

  1.在项目的“Groups & Files”面板上,展开“Targets”

  2.Control+点击或右击AudioPlayer

  3.选择“Add > ExistinFrameworks…”

  4.点击Linked Libraries下左下方的+按钮

  5.选择“AVFoundation Framework“并按Add

  6.“AVFoundation framewoks”将出现在“Linked Libraries”下,关闭窗口
 
下面,我们将引入AVFoundation的头文件

  1.展开项目“Group & Files”面板下AudioPlayer项目

  2.打开Classes文件夹

  3.选取AudioPlayerViewController.h进行编辑

  4.更改文件  。更改以下粗体字部分:

  1.  #import <UIKit/UIKit.h> 
  2. #import <AVFoundation/AVFoundation.h> 
  3.  
  4. @interface AudioPlayerViewController :  UIViewController   
  5. {  
  6.     AVAudioPlayer  *audioPlayer;  
  7. }  
  8. @end  

  添加音频文件

  我们需要一段音频文件来进行播放  。文件为audiofie.mp3  。我们将其加入项目中:

  按Control再左击或右击项目的“Group & Files”面板中的“Resources”文件夹

  从上下文菜单中选取“Add > Existing Files…”

  找到并选择要导入的音频文件,按“Add”

  (有必要的话)选定“Copy iteminto destination group’s folder”方框并按“Add”

  开始播放音频

  我们在ViewDidLoad中启动音频播放:

  1.解除ViewDidLoad方法的注解

  2.更改如下,见粗体部分:

  1. - (void)viewDidLoad  
  2.  
  3.    [super  viewDidLoad];  
  4.  
  5.    NSURL  *url = [NSURL fileURLWithPath:[NSString    
  6.        stringWithFormat:@"%@/audiofile.mp3",  [[NSBundle mainBundle]  resourcePath]]];  
  7.    NSError  *error;  
  8.    audioPlayer  = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];  
  9.    audioPlayer.numberOfLoops  = -1;  
  10.    if  (audioPlayer == nil)  
  11.        NSLog([error  description]);  
  12.    else  
  13.         [audioPlayer  play];  

  AVAudioPlayer是通过URL初始化的,所以我们首先要创立一个指向资源文件夹中音频文件的URL  。将音频播放器的numberOfLoops属性设为负数使得播放无限循环  。配置好音频播放器后,我们向播放器对象发送播放消息来启动播放  。

  记住在dealloc方法中释放audioPlayer  。改变见粗体部分:

  1. - (void)dealloc   
  2.  
  3.    [audioPlayer  release];  
  4.    [super  dealloc];  
  5.  }  

  更多功能

  你可以调节播放器音量,查看/设定播放的时间,暂停或停止播放:

  1. audioPlayer.volume = 0.5; // 0.0 - no  volume; 1.0 full volume   
  2. NSLog(@"%f seconds played so  far", audioPlayer.currentTime);  
  3. audioPlayer.currentTime = 10; // jump to  the 10 second mark  
  4. [audioPlayer pause];  
  5. [audioPlayer stop]; // Does not reset currentTime; sending play resumes  

  最后,你还可以实现AVAudioPlayer Delegate协议,比如说,在音频播放结束时得到通知,这样你有可能移动到播放列表的下一首歌  。

然后自己把事件一绑定就行

本文转自编程小翁博客园博客,原文链接:http://www.cnblogs.com/wengzilin/archive/2012/03/18/2404684.html,如需转载请自行联系原作者

相关文章
|
移动开发 前端开发 Android开发
前端html input =“file“ ios/安卓解决无法选择图库/拍照问题
前端html input =“file“ ios/安卓解决无法选择图库/拍照问题
2623 0
|
Web App开发 XML Java
java.lang.IllegalStateException: Async support must be enabled on a servlet and for all filters invo
Spring MVC 项目在使用 DeferredResult 实现异步接口时出现错误。 完整错误信息如下: 十一月 03, 2017 8:59:53 上午 org.apache.catalina.
2726 0
获取apk的签名信息
在接入第三方功能时,经常要注册提交apk的签名信息 (sha1签名)?,下面列出相关步骤。 获取apk签名信息的步骤: 1)修改apk后缀名为zip,解压得到其中的META-INF文件夹; 2)把META-INF文件夹放到C盘根目录下; 3)在dos面板中,  敲入命令:  keytool -printcert -file C:\META-INF\CERT.
5809 0
|
SQL 关系型数据库 MySQL
MySQL多条SQL语句合并实现
【5月更文挑战第11天】
475 0
|
存储 easyexcel Java
|
Linux
如何在 CentOS 7 linux上安装和使用 FFmpeg
如何在 CentOS 7 linux上安装和使用 FFmpeg
848 0
|
存储 异构计算 Python
解决numpy.core._exceptions.MemoryError: Unable to allocate 1.04 MiB for an array
但实际上它保存的不是模型文件,而是参数文件文件。在模型文件中,存储完整的模型,而在状态文件中,仅存储参数。因此,collections.OrderedDict只是模型的值。
2380 0
|
Linux
Linux安装已编译好的FFmpeg,基于centos7
Linux安装已编译好的FFmpeg,基于centos7
471 0
|
存储 域名解析 缓存
集成了阿里云的EMAS相关SDK怎么处理隐私问题?
EMAS中包含一系列SDK,开发者可能集成一个或者多个,有的SDK会涉及到隐私合规问题导致应用上架审核不通过, 以下一些方案可以参考