要給工程中添加音頻,首先要導入音頻的框架 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];