这篇文章主要介绍了iOS App中调用AVAudioPlayer播放音频文件的用法,AVAudioPlayer仅能播放本地文件而不能添加网络源,实例代码为Objective-C,需要的朋友可以参考下
要给工程中添加音频,首先要导入音频的框架 AVFoundation.framework
然后新建一个类继承于UIViewController, 我这里就叫FirstVC.
首先在 AppDelegate.m中初始化根视图
#import "AppDelegate.h"
#import "FirstVC.h"
@implementation AppDelegate
- (void)dealloc
{
[_window release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
FirstVC *firstVC = [[FirstVC alloc] init];
self.window.rootViewController = firstVC;
[firstVC release];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
然后在FirstVC.h中导入AVFoundation框架
#import <UIKit/UIKit.h>
//要想使用封装好的音频类,导入框,导入类头文件,缺一不可;
#import <AVFoundation/AVFoundation.h>
@interface FirstVC : UIViewController<AVAudioPlayerDelegate>
{
AVAudioPlayer *avAudioPlayer; //播放器player
UIProgressView *progressV; //播放进度
UISlider *volumeSlider; //声音控制
NSTimer *timer; //监控音频播放进度
}
@end
然后在FirstVC.m里的viewDidLoad方法里填写代码 你需要导入一个音频才可以播放 像添加图片一样,直接拖到工程里就可以了
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
//初始化三个button
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setFrame:CGRectMake(100, 100, 60, 40)];
[button setTitle:@"Play" forState:UIControlStateNormal];
[button addTarget:self action:@selector(play) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button1 setFrame:CGRectMake(100, 150, 60, 40)];
[button1 setTitle:@"pause" forState:UIControlStateNormal];
[button1 addTarget:self action:@selector(pause) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button1];
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button2 setFrame:CGRectMake(100, 200, 60, 40)];
[button2 setTitle:@"stop" forState:UIControlStateNormal];
[button2 addTarget:self action:@selector(stop) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button2];
//从budle路径下读取音频文件 轻音乐 - 萨克斯回家 这个文件名是你的歌曲名字,mp3是你的音频格式
NSString *string = [[NSBundle mainBundle] pathForResource:@"轻音乐 - 萨克斯回家" ofType:@"mp3"];
//把音频文件转换成url格式
NSURL *url = [NSURL fileURLWithPath:string];
//初始化音频类 并且添加播放文件
avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
//设置代理
avAudioPlayer.delegate = self;
//设置初始音量大小
// avAudioPlayer.volume = 1;
//设置音乐播放次数 -1为一直循环
avAudioPlayer.numberOfLoops = -1;
//预播放
[avAudioPlayer prepareToPlay];
//初始化一个播放进度条
progressV = [[UIProgressView alloc] initWithFrame:CGRectMake(20, 50, 200, 20)];
[self.view addSubview:progressV];
[progressV release];
//用NSTimer来监控音频播放进度
timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self
selector:@selector(playProgress)
userInfo:nil repeats:YES];
//初始化音量控制
volumeSlider = [[UISlider alloc] initWithFrame:CGRectMake(20, 70, 200, 20)];
[volumeSlider addTarget:self action:@selector(volumeChange)
forControlEvents:UIControlEventValueChanged];
//设置最小音量
volumeSlider.minimumValue = 0.0f;
//设置最大音量
volumeSlider.maximumValue = 10.0f;
//初始化音量为多少
volumeSlider.value = 5.0f;
[self.view addSubview:volumeSlider];
[volumeSlider release];
//声音开关控件(静音)
UISwitch *swith = [[UISwitch alloc] initWithFrame:CGRectMake(100, 20, 60, 40)];
[swith addTarget:self action:@selector(onOrOff:) forControlEvents:UIControlEventValueChanged];
//默认状态为打开
swith.on = YES;
[self.view addSubview:swith];
[swith release];
}
相应的自定义方法代码如下
//播放
- (void)play
{
[avAudioPlayer play];
}
//暂停
- (void)pause
{
[avAudioPlayer pause];
}
//停止
- (void)stop
{
avAudioPlayer.currentTime = 0; //当前播放时间设置为0
[avAudioPlayer stop];
}
//播放进度条
- (void)playProgress
{
//通过音频播放时长的百分比,给progressview进行赋值;
progressV.progress = avAudioPlayer.currentTime/avAudioPlayer.duration;
}
//声音开关(是否静音)
- (void)onOrOff:(UISwitch *)sender
{
avAudioPlayer.volume = sender.on;
}
//播放音量控制
- (void)volumeChange
{
avAudioPlayer.volume = volumeSlider.value;
}
//播放完成时调用的方法 (代理里的方法),需要设置代理才可以调用
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
[timer invalidate]; //NSTimer暂停 invalidate 使...无效;
}
最后别忘了释放内存
- (void)dealloc
{
[avAudioPlayer release];
[progressV release];
[volumeSlider release];
[timer release];
[super dealloc];
}
当然,你也可以再定义一个UISlider来控制播放进度.
最后运行起来的就是这个样子
如果想要播放网络音乐,那么遗憾的是iOS中的AVAudioPlayer不支持边下边播,所以只能下载到本地再播放。
方法:
NSString *urlStr = @"http://…………xxx.mp3";
NSURL *url = [[NSURL alloc]initWithString:urlStr];
NSData * audioData = [NSData dataWithContentsOfURL:url];
//将数据保存到本地指定位置
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@.mp3", docDirPath , @"temp"];
[audioData writeToFile:filePath atomically:YES];
//播放本地音乐
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
[player play];
注意代码中的player是类的私有变量,因为在ARC模式下如果定义局部变量,出了作用域后对象会被销毁。这个问题也是纠结了好久才搞明白。参见链接
当然也可以不保存文件,只是将player的构造方法改为用data实例化即可。
总结:
下面说一下我遇到的各种问题:
1、由于添加了All Exception断点,导致每次都在初始化的时候自动断到,因为不是OC异常,又无异常信息显示。这时应该编辑断点,将其类型由All改为OC。这个异常并不会导致程序的崩溃,所以可以不作处理。
2、网上有的说不能播放,解决方案是应该在 AppDelegate.m文件中的
application didFinishLaunchingWithOptions 添加这样一句代码:
[[AVAudioSession sharedInstance]setCategory:AVAudioSessionCategoryPlaybackerror:nil];
本文标题为:详解iOS App中调用AVAudioPlayer播放音频文件的用法
基础教程推荐
- iOS Crash常规跟踪方法及Bugly集成运用详细介绍 2023-01-18
- MVVMLight项目Model View结构及全局视图模型注入器 2023-05-07
- iOS中如何判断当前网络环境是2G/3G/4G/5G/WiFi 2023-06-18
- Flutter进阶之实现动画效果(三) 2022-10-28
- Android开发Compose集成高德地图实例 2023-06-15
- Android实现短信验证码输入框 2023-04-29
- IOS获取系统相册中照片的示例代码 2023-01-03
- iOS开发使用XML解析网络数据 2022-11-12
- iOS开发 全机型适配解决方法 2023-01-14
- Android Compose自定义TextField实现自定义的输入框 2023-05-13