簡單做一個播放音樂的小demo:
- 搭建界面,放三個按鈕,播放、暫停、停止
- 播放音效,因為文件小,所以不需要進行什么控制。音樂文件的時間比較長,那就會有暫停播放、繼續播放這些控制的需求。那就不能簡單的搞一個soundID去播放,而是需要用到AVAudioPlayer這個類。
- 創建的時候,需要指定url,一個url對應一個對象,并且是只讀的,不能修改。所以說,如果你想播放一首新的音樂,就需要重新創建一個AVAudioPlayer對象
- prepareToPlay,準備播放,把音頻文件加載到內存中。也可以直接調用play 方法,它就會隱式調用prepareToPlay方法
- pause,暫定;stop,停止。
蘋果這里有一個非常不爽的地方,停止的時候,默認也會繼續播放,如果需要真正挺值得話,就要將時間進行歸零操作。- isPlaying 是否正在播放
- duration 當前播放音樂的總時長
- currentTime 當前播放的時間點
下面是實現代碼:
ViewController.m
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
/**
1. 需要使用AVFoundatiaon框架
2. 創建音樂播放器
3. 根據需求, 進行播放/暫停/停止
*/
@interface ViewController ()
@property (nonatomic, strong) AVAudioPlayer *player;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 創建音樂播放器
//1. 獲取URL路徑
NSURL *url = [[NSBundle mainBundle] URLForResource:@"xxx.mp3" withExtension:nil];
//2. 創建一個error對象
NSError *error;
//3. 創建音樂播放器
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
if (error) {
NSLog(@"有錯誤產生是的邏輯判斷");
}
}
- (IBAction)playClick:(id)sender {
//1. 準備播放 --> 將音頻文件加載到內存中 --> 這句話可以不寫 --> play會隱式調用prepareToPlay方法. 但是規范來說, 還是會寫上
[self.player prepareToPlay];
//2. 開始播放
[self.player play];
}
- (IBAction)pauseClick:(id)sender {
// 暫停播放
[self.player pause];
}
- (IBAction)stopClick:(id)sender {
// 停止播放
[self.player stop];
// 歸零操作 / 時間重置 currentTime--> 秒為單位
self.player.currentTime = 0;
}
@end