iOS中AVFoundation的简单使用—音乐的播放
生活随笔
收集整理的這篇文章主要介紹了
iOS中AVFoundation的简单使用—音乐的播放
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
#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];// 首先創(chuàng)建一個(gè)label用來顯示音樂的總時(shí)長(zhǎng)和當(dāng)前的時(shí)間;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; // 創(chuàng)建一個(gè)播放對(duì)象;AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];if (error) {NSLog(@"創(chuàng)建播放對(duì)象失敗:%@",error);return;}else {self.player = player; // 這一步必須執(zhí)行,只有各就各位(創(chuàng)建播放對(duì)象)、預(yù)備(prepareToPlay:準(zhǔn)備播放)之后發(fā)令槍才會(huì)響起(才能夠play);[self.player prepareToPlay];} }//定時(shí)自動(dòng)調(diào)用的方法,用于隨時(shí)設(shè)置label顯示的播放時(shí)間。 - (void)setUpTimer {//isPlaying為BOOL屬性,播放對(duì)象是否正在播放。if (self.player.isPlaying) { // self.player.currentTime,如果player正在播放此屬性為當(dāng)前的播放時(shí)間,也可以設(shè)置player的播放偏移(便宜到指定的時(shí)間點(diǎn) 開始播放)。 // self.player.duration,此屬性為player播放音樂的總時(shí)長(zhǎng)。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 暫停;還有十個(gè)stop的方法,但是現(xiàn)在與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當(dāng)然除了這些還有
volume:設(shè)置聲音的大小為float值取值范圍為0.0-1.0;
enableRate:BOOL是否可已設(shè)置音樂的播放速率;
rate:float在enableRate設(shè)置為YES時(shí)可以設(shè)置音樂的播放速率,默認(rèn)為1,0.5即為半速,2.0即為雙倍速。
numberOfLoops:loop即為循環(huán)。number是次數(shù)。由此可證numberOfLoops即為循環(huán)次數(shù)。。。
?
轉(zhuǎn)載于:https://my.oschina.net/ruiruiheshui/blog/673036
總結(jié)
以上是生活随笔為你收集整理的iOS中AVFoundation的简单使用—音乐的播放的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [MySQL 优化] 移除多余的chec
- 下一篇: 数据结构---队列C语言实现