天天看點

iOS - 音頻播放簡介音頻播放

音頻播放

1.利用System Sound Services

System Sound Services提供C語言風格接口用于播放短的聲音,如果對應的裝置支援振動,還可以調用振動。

使用 System Sound Services限制

1.音頻檔案播放長度不能大于30秒

2.必須是線性的音頻格式:PCM or IMA4 (IMA/ADPCM)

3.檔案格式必須是.caf, .aif, or .wav file

4.聲音大小不能改變,依賴于裝置設定

5.聲音立即播放

6.不支援循環播放 立體聲和定位

7.不支援同時播放,即一次隻能播放一個聲音

執行個體展示

@interface ViewController ()
//用于表示系統音頻檔案對象
@property (nonatomic, assign) SystemSoundID soundFileObject;
//可以了解為音頻檔案的位置和目錄
@property (nonatomic, assign) CFURLRef soudnFileURLRef;
@end
           
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *soundFileURL = [[NSBundle mainBundle] URLForResource:@"Two" withExtension:@"caf"];
self.soudnFileURLRef = (CFURLRef)[soundFileURL retain];
OSStatus ret = AudioServicesCreateSystemSoundID(self.soudnFileURLRef, &_soundFileObject);
if (ret != 0) {
NSLog(@"create systemSound id failure。");
}
           

//系統聲音播放

- (IBAction)playSystemSoud:(UIButton *)sender
{
AudioServicesPlaySystemSound(self.soundFileObject);
}
           

//系統警告聲音播放

- (IBAction)playAlterSound:(UIButton *)sender {
AudioServicesPlayAlertSound(self.soundFileObject);
}
           

//震動播放,前提是裝置需要支援震動

- (IBAction)playVibate:(UIButton *)sender {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
           

2.利用AVAudioPlayer展示本地音頻

1.基本介紹

AVPlayer的執行個體對象,調用音頻播放器可以播放來自檔案和記憶體的音頻資料。

在音頻播放方面,蘋果公司推薦使用AVPlayer,除非你播放的音頻資料是來自網絡的流媒體,或者需要調用更低層的I/O接口播放音頻資料。

可以播放在iOS上可用的任意一種音頻檔案格式

AVPlayer的控制能力

1.播放任何時長的音樂

2.播放來自檔案或記憶體的音頻資料

3.支援循環播放

4.能同時播放多個音頻資料,需要多個執行個體

5.可以直接定位到音頻播放的任意一個位置,支援快進,快退

2.AVAudioPlayer常用屬性

1、音量


player.volume =0.8; //0.0-1.0之間

2、循環次數 


player.numberOfLoops =3; //預設隻播放一次,如果是-1表示無限循環

3、播放位置   


 player.currentTime =15.0; //可以指定從任意位置開始播放

4、聲道數


 NSUInteger channels = player.numberOfChannels; //隻讀屬性

5、持續時間


NSTimeInterval duration = player.duration; //擷取持續時間

3.例子展示

向大家展示的功能是一個簡單的播放器,可以用一個UISlider控制進度和顯示進度,用另一個UISlider控制音量,一個播放和暫停按鈕,一個停止按鈕。

1.在檔案頭加入頭檔案,因為不加入此頭檔案,音頻類無法使用

#import <AVFoundation/AVFoundation.h>

2.代碼

xib上拉過來的一些屬性

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UISlider *sliderVolume;
@property (weak, nonatomic) IBOutlet UISlider *sliderProgress;
@property (weak, nonatomic) IBOutlet UIButton *btnPlayAndPause;
@property (strong,nonatomic) AVAudioPlayer *audioPlayer;
@end
           

//在viewDidLoad中設定一些屬性

- (void)viewDidLoad {
[super viewDidLoad];
// 建立表示檔案路徑的對象,音樂為本地音樂
NSURL *soundFileURL = [[NSBundle mainBundle] URLForResource:@"倩女幽魂" withExtension:@"mp3"];
// 執行個體化audioPlayer對象
NSError *error = nil;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:&error];
if (nil != error) {
NSLog(@"create AVAudioPlaer instance error.%@",error);
return;
}
// 如果設定成為-1無限循環播放, 類似于單典循環
self.audioPlayer.numberOfLoops = 2;
// 準備播放audiPlayer
[self.audioPlayer prepareToPlay];
self.sliderVolume.value = 0.5;
self.audioPlayer.volume = self.sliderVolume.value;
// 對界面對象做一些配置
self.sliderProgress.minimumValue = 0;
self.sliderProgress.maximumValue = self.audioPlayer.duration;
}
           

//點選播放按鈕,開發播放音樂

- (IBAction)onPalyAndPause:(UIButton *)sender {
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
if ([self.audioPlayer isPlaying]) {
[self.btnPlayAndPause setTitle:@"播放" forState:UIControlStateNormal];
[self.audioPlayer pause];
}else
{
[self.btnPlayAndPause setTitle:@"暫停" forState:UIControlStateNormal];
[self.audioPlayer play];
}
           

//停止按鈕的事件

- (IBAction)onStop:(UIButton *)sender {
if ([self.audioPlayer isPlaying]) {
[self.audioPlayer stop];
self.audioPlayer.currentTime = 0;
// 如果調用stop之後, 我們城要調用prepareToPlay為下次播放做準備
[self.audioPlayer prepareToPlay]; 
[self.btnPlayAndPause setTitle:@"播放" forState:UIControlStateNormal];
}
}
           

//利用定時器讓進度條顯示歌曲進度

- (void)onTimer:(NSTimer *)timer
{
self.sliderProgress.value = self.audioPlayer.currentTime;
}
           

//控制聲音大小

- (IBAction)onSliderValueChange:(UISlider *)sender {
self.audioPlayer.volume = sender.value;
}
           

//控制進度

- (IBAction)onSliderProgresChange:(UISlider *)sender {
self.audioPlayer.currentTime = sender.value;
}
           

3.利用AVPlayer展示音頻

1.簡單的音頻展示

- (void)viewDidLoad
{
[super viewDidLoad];
NSString *strURL = @"http://music.baidu.com/data/music/file?link=http://yinyueshiting.baidu.com/data2/music/123850666/12385061093600128.mp3?xcode=af4496becdf45f97ed0afeb1a7a3796c17a5fcb5a3da7702&song_id=123850610";
self.player = [[AVPlayer alloc]initWithURL:[NSURL URLWithString:strURL]];
}
           
- (IBAction)onPlayButton:(UIButton *)sender {
[self.player play];
}
           

點選播放按鈕

即可播放聲音,由于蘋果公司封裝的很好,是以十分容易

2.如何讓音頻支援背景

在 - (void)viewDidLoad中調用方法

[self setAVPlayerSupportBackgroundPlay];
           

//讓音頻支援背景方法

- (void)setAVPlayerSupportBackgroundPlay
{
UIDevice *device = [UIDevice currentDevice];
if ([device respondsToSelector:@selector(isMultitaskingSupported)]) {
if (device.multitaskingSupported) {
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *error = nil;
[audioSession setCategory:AVAudioSessionCategoryPlayback error:&error];
if (error!=nil) {
NSLog(@"active category error");
}
}
}else
{
NSLog(@"unSupported background");
}
}
           

同時需要在plist檔案中增加一行 required background modes

把對應的value值設定為:App plays audio or streams audio/video using AirPlay

3.如何支援遠端控制(耳機)

//系統會回調此方法,用來支援遠端控制程式

//界面将要呈現的時候, ,設定開始接受遠端事件。前且将目前ViewController變成第一響應者

- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
           
<p>//界面将要消失的時候, 設定結束按收遠端事件,并且将目前ViewController取消第一響應者, 以達到不接收遠端事件的目的。</p><div>
</div>- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];
}
           

//此方法系統自己調用,用來執行遠端控制功能

<p>
</p>- (void)remoteControlReceivedWithEvent:(UIEvent *)event
{
if (event.type == UIEventTypeRemoteControl) {
switch (event.subtype) {
case UIEventSubtypeRemoteControlPause:
//調用音頻檔案的暫停操作
{
[self pauseMusic:nil];
}
break;
case UIEventSubtypeRemoteControlPlay:
//調用播放器的播放動作
{
[self playMusic];
}
break;
case UIEventSubtypeRemoteControlPreviousTrack:
{
NSString *str = @"http://music.baidu.com/data/music/file?link=http://yinyueshiting.baidu.com/data2/music/264925/2648931413748861128.mp3?xcode=9d798c1a7c0ff254b41b4256fdb8922c718421d4f4bf1a8b&song_id=264893";
self.player = [AVPlayer playerWithURL:[NSURL URLWithString:str]];
[self playMusic];
//播放上一首音頻資料
}
break;
case UIEventSubtypeRemoteControlNextTrack:
{
//播放下一首音頻檔案
NSString *str = @"http://music.baidu.com/data/music/file?link=http://yinyueshiting.baidu.com/data2/music/122870192/58375641413802861128.mp3?xcode=840e0f17068984974e7ec0f052a053fdeda79a93c0bfc1e7&song_id=5837564";
self.player = [AVPlayer playerWithURL:[NSURL URLWithString:str]];
[self playMusic];
}
break;
default:
break;
}
}
           
- (void)pauseMusic:(UIButton*)sender
{
[self.player pause];
} 
           
- (void)playMusic
{
[self.player play];
}
           

4.利用AVAudioRecorder錄制音頻

1.頭檔案

在頭檔案中加#import <AVFoundation/AVFoundation.h>

2.成員變量

@interface ViewController ()
@property (nonatomic, strong) AVAudioRecorder audioReconder; @property (nonatomic, strong) AVAudioPlayer audioPlayer;
@property (nonatomic, strong) NSURL soundFilePath; @property (weak, nonatomic) IBOutlet UIButton btnReconder; @property (weak, nonatomic) IBOutlet UIButton *btnPlay;
@end
           

3.viewDidLoad

- (void)viewDidLoad {
[super viewDidLoad];
self.soundFilePath = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/recordTest.caf",[[NSBundle mainBundle] resourcePath]]];
NSError *error = nil;
NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] initWithCapacity:10];
NSNumber *formatObject = [NSNumber numberWithInt:kAudioFormatAppleIMA4];
[recordSettings setObject:formatObject forKey:AVFormatIDKey];
[recordSettings setObject:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSettings setObject:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey]; //1.單聲道 2.立體聲
[recordSettings setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey]; //采樣位
[recordSettings setObject:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
self.audioReconder = [[AVAudioRecorder alloc] initWithURL:self.soundFilePath settings:recordSettings error:&error];
if (error != nil) {
NSLog(@"instance audioReconder error.%@",error);
}
[self.audioReconder prepareToRecord];
           

4.點選錄制按鈕開始錄制

- (IBAction)recordAudio:(UIButton *)sender {
if ([self.audioReconder isRecording]) {
[self.btnReconder setTitle:@"錄音" forState:UIControlStateNormal];
[self.audioReconder stop];
}else
{
[self.btnReconder setTitle:@"停止" forState:UIControlStateNormal];
[self.audioReconder record];
}
}
           

5.點選播放按鈕,播放音樂

- (IBAction)playAudio:(UIButton *)sender {

if ([self.audioPlayer isPlaying]) { [self.btnPlay setTitle:@"播放" forState:UIControlStateNormal]; [self.audioPlayer pause]; }else { NSError *error = nil; self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:self.soundFilePath error:&error]; if (error != nil) { NSLog(@"instance audioPlayer error.%@",error); } [self.audioPlayer prepareToPlay]; [self.btnPlay setTitle:@"暫停" forState:UIControlStateNormal]; [self.audioPlayer play];

} }