导入
#import <AVFoundation/AVFoundation.h>
代理
@interface ViewController ()<AVAudioPlayerDelegate>
@property (nonatomic, strong) AVAudioPlayer *player; // 播放对象属性
切换按钮状态
self.playMusic.selected = !self.playMusic.selected;
开始播放
[self.player play];
暂停播放
[self.player pause];
获得已经播放的时间
NSTimeInterval currentTime = self.player.currentTime;
获得歌曲剩余时间
NSTimeInterval endTime = self.player.duration - currentTime;
音乐的长度
self.player.duration;
获得音乐路径(URL)
NSString *filePath = [[NSBundle mainBundle] pathForResource:musicName ofType:@"mp3"];
NSURL *URL = [NSURL fileURLWithPath:filePath];
初始化播放对象
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:URL error:nil];
self.player.delegate = self;
准备播放
[self.player prepareToPlay];
完整代码
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()<AVAudioPlayerDelegate>
@property (nonatomic, strong) AVAudioPlayer *player; // 播放对象属性
@property (nonatomic, strong) NSArray *musicNameArray; // 名称数组
- (NSArray *)musicNameArray {
if (!_musicNameArray) {
_musicNameArray = @[@"被情所伤害过的人-伤感中文慢摇",@"Deemo Title Song - Website Version",@"Release My Soul",@"李克勤 - 月半小夜曲"];
}
return _musicNameArray;
}
// 切换按钮状态
self.playMusic.selected = !self.playMusic.selected;
// 开始播放
[self.player play];
// 暂停播放
[self.player pause];
// 按钮状态
if (![self.player isPlaying])
self.playMusic.selected = NO;
// 获得已经播放的时间
NSTimeInterval currentTime = self.player.currentTime;
// 计算分钟数
NSInteger minute = currentTime / 60;
// 计算秒数
NSInteger second = (NSInteger)currentTime % 60;
// 赋值
self.playTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld",minute,second];
// 获得歌曲剩余时间
NSTimeInterval endTime = self.player.duration - currentTime;
// 音乐的长度
self.player.duration;
// 第一步:获得音乐路径(URL)
NSString *filePath = [[NSBundle mainBundle] pathForResource:musicName ofType:@"mp3"];
NSURL *URL = [NSURL fileURLWithPath:filePath];
// 屏蔽地址异常
if (!URL) {
return;
}
// 初始化播放对象
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:URL error:nil];
self.player.delegate = self;
// 准备播放
[self.player prepareToPlay];