iOS中AVFoundation的简单使用—音乐的播放
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                iOS中AVFoundation的简单使用—音乐的播放
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                2019獨角獸企業重金招聘Python工程師標準>>>
#import "ViewController.h" #import <AVFoundation/AVFoundation.h>@interface ViewController ()@property (nonatomic, strong)AVAudioPlayer *player;@property (nonatomic, weak)UILabel *timer;@property (nonatomic, strong)NSTimer *t;@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];// 首先創建一個label用來顯示音樂的總時長和當前的時間;UILabel *timer = [[UILabel alloc]initWithFrame:CGRectMake(0, 0,100, 30)];self.timer = timer;timer.textAlignment = NSTextAlignmentCenter;self.timer.center = self.view.center;[self.view addSubview:timer]; // 獲取音樂文件的url;NSString *path = [[NSBundle mainBundle]pathForResource:@"Groove Coverage-Runaway" ofType:@"mp3"];NSURL *url = [NSURL fileURLWithPath:path];NSError *error = nil; // 創建一個播放對象;AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];if (error) {NSLog(@"創建播放對象失敗:%@",error);return;}else {self.player = player; // 這一步必須執行,只有各就各位(創建播放對象)、預備(prepareToPlay:準備播放)之后發令槍才會響起(才能夠play);[self.player prepareToPlay];} }//定時自動調用的方法,用于隨時設置label顯示的播放時間。 - (void)setUpTimer {//isPlaying為BOOL屬性,播放對象是否正在播放。if (self.player.isPlaying) { // self.player.currentTime,如果player正在播放此屬性為當前的播放時間,也可以設置player的播放偏移(便宜到指定的時間點 開始播放)。 // self.player.duration,此屬性為player播放音樂的總時長。self.timer.text = [NSString stringWithFormat:@"%d:%d/%d:%d",(int)self.player.currentTime/60,(int)self.player.currentTime%60,(int)self.player.duration/60,(int)self.player.duration%60];}else {self.timer.text = @"等待播放";}}-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {if (self.player.isPlaying) {[self.t invalidate]; // pause 暫停;還有十個stop的方法,但是現在與pause等效了。[self.player pause];}else {NSTimer *t = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(setUpTimer) userInfo:nil repeats:YES];self.t = t; // play:播放。[self.player play];}}- (void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];// Dispose of any resources that can be recreated. }@end當然除了這些還有
volume:設置聲音的大小為float值取值范圍為0.0-1.0;
enableRate:BOOL是否可已設置音樂的播放速率;
rate:float在enableRate設置為YES時可以設置音樂的播放速率,默認為1,0.5即為半速,2.0即為雙倍速。
numberOfLoops:loop即為循環。number是次數。由此可證numberOfLoops即為循環次數。。。
?
轉載于:https://my.oschina.net/ruiruiheshui/blog/673036
總結
以上是生活随笔為你收集整理的iOS中AVFoundation的简单使用—音乐的播放的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: [MySQL 优化] 移除多余的chec
- 下一篇: Nginx配置之基于域名的虚拟主机
