本文記錄初次接觸 iOS UI 開發時所做的一個簡易音訊播放器,用來熟悉基本控制元件與 Target-Action 回呼模式。播放器運用到 UIProgressView(進度條)、UILabel(顯示時間)、UIImageView(圖片)、UISegmentedControl(播放/暫停)、UISlider(音量),並以 NSTimer 定時更新播放時間,最後透過 AVFoundation.framework 的 AVAudioPlayer 播放音訊。
點擊播放會播放預設歌曲,同時顯示進度與目前時間;下方的 slider 可調整音量。
首先建立 Single View 的 iPhone 專案,在 ViewController.m 中用類別擴展宣告元件與方法:
@interface ViewController ()
@property (strong, nonatomic) UIImageView *backView;
@property (strong, nonatomic) UIProgressView *progress;
@property (strong, nonatomic) UISegmentedControl *segment;
@property (strong, nonatomic) UISlider *slider;
@property (strong, nonatomic) NSTimer *timer;
@property (strong, nonatomic) UILabel *label;
@property (strong, nonatomic) UIImageView *imageView;
@property (strong, nonatomic) AVAudioPlayer *player;
- (void)tapSegment;
- (void)time;
- (void)changeVo;
@end
在 viewDidLoad 中完成元件配置。以下為幾個關鍵片段:
// 加入背景圖片並置於最底層
self.backView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 20, 320, 480)];
self.backView.image = [UIImage imageNamed:@"background"];
[self.view insertSubview:self.backView atIndex:0];
// 進度條
self.progress = [[UIProgressView alloc] initWithFrame:CGRectMake(30, 60, 240, 10)];
[self.view addSubview:self.progress];
self.progress.progress = 0;
// 播放/暫停的 segment,並註冊回呼
self.segment = [[UISegmentedControl alloc] initWithItems:@[@"Play", @"Pause"]];
self.segment.frame = CGRectMake(110, 255, 100, 40);
[self.segment addTarget:self action:@selector(tapSegment) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:self.segment];
// 配置播放器
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle pathForResource:@"music" ofType:@"mp3"];
NSURL *musicURL = [NSURL fileURLWithPath:path];
NSError *error;
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:&error];
// 每秒更新一次時間
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(time) userInfo:nil repeats:YES];
// 音量 slider
self.slider = [[UISlider alloc] initWithFrame:CGRectMake(100, 300, 120, 50)];
[self.slider addTarget:self action:@selector(changeVo) forControlEvents:UIControlEventValueChanged];
self.slider.minimumValue = 1;
self.slider.maximumValue = 10;
// 改變音量
-(void)changeVo {
self.player.volume = self.slider.value;
}
// 更新時間與進度
-(void)time {
NSTimeInterval totalTimer = self.player.duration;
NSTimeInterval currentTime = self.player.currentTime;
self.progress.progress = (currentTime / totalTimer);
NSTimeInterval currentM = currentTime / 60;
currentTime = (int)currentTime % 60;
NSTimeInterval totalM = totalTimer / 60;
totalTimer = (int)totalTimer % 60;
NSString *timeString = [NSString stringWithFormat:@"%02.0f:%02.0f|%02.0f:%02.0f", currentM, currentTime, totalM, totalTimer];
self.label.text = timeString;
}
// 依 segment 選擇播放或暫停
-(void)tapSegment {
int isOn = self.segment.selectedSegmentIndex;
if (isOn == 0) {
[self.player play];
} else {
[self.player pause];
}
}