AVFoundation框架,看到這個名字的時候小激動一下,仔細想一下應該是audio,video的意思吧,后來去翻蘋果的文檔,原來是** audiovisual(視聽)**的意思。單詞不一樣,不過意思差不多吧,主要是用來處理音頻
和視頻
的.
下面的是從官方文檔中拿出來的
frameworksBlockDiagram_2x.png
注意:在使用時,應盡量使用更高級別的控件(這些控件經過進一步的封裝,使用起來可能會更容易一些)
- 如果只是想播放視頻,應該使用AVKit框架。
- 在IOS中,如果只是想錄制視頻,可以使用UIKit框架(
UIImagePickerController
).
iOS中的音頻
- 音效(時間一般比較短)
- 音樂
- 錄音
1.播放音效
主要實現下面的幾個方法
- AudioServicesCreateSystemSoundID(CFURLRef inFileURL,SystemSoundID*outSystemSoundID)
- AudioServicesPlaySystemSound(SystemSoundID inSystemSoundID)
- AudioServicesDisposeSystemSoundID(SystemSoundID inSystemSoundID);
- (void)playSoundWithFileName:(NSString *)fileName {
//定義一個soundID用來接收系統生成的聲音ID
SystemSoundID soundID=0;
// 獲取資源文件
NSURL *url = [[NSBundle mainBundle] URLForResource:fileName withExtension:nil];
if (url == nil) return;
// 獲取音頻的soundID
AudioServicesCreateSystemSoundID(CFBridgingRetain(url), &soundID);
AudioServicesPlaySystemSound(soundID);
}
2. 播放音樂
To play sound files, you can use AVAudioPlayer
.
播放音樂文件,使用AVAudioPlayer。進到頭文件看一下,內容也不是很多,大概看一些應該就可以上手了。
主要的幾個方法:
- (nullable instancetype)initWithContentsOfURL:(NSURL *)url error:(NSError **)outError;
- (nullable instancetype)initWithData:(NSData *)data error:(NSError **)outError;
/* transport control */
/* methods that return BOOL return YES on success and NO on failure. */
- (BOOL)prepareToPlay; /* get ready to play the sound. happens automatically on play. */
- (BOOL)play; /* sound is played asynchronously. */
- (void)pause; /* pauses playback, but remains ready to play. */
- (void)stop; /* stops playback. no longer ready to play. */
示例代碼:
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
@property (nonatomic,strong) AVAudioPlayer *player;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [[NSBundle mainBundle] URLForResource:@"童話.mp3" withExtension:nil];
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
// 準備播放
[self.player prepareToPlay];
}
- (IBAction)play {
[self.player play];
}
- (IBAction)pause {
[self.player pause];
}
- (IBAction)stop {
[self.player pause];
}
@end
3. 錄音
To record audio, you can use AVAudioRecorder
.
記錄音頻信息,需要使用AVAudioRecorder
。這個類和AVAudioPlayer
非常類似,不過錄音的時候需要設置參數。
- (nullable instancetype)initWithURL:(NSURL *)url settings:(NSDictionary<NSString *, id> *)settings error:(NSError **)outError;
這個settings的參數可以參考AV Foundation Audio Settings Constants.
// setting[AVFormatIDKey] = @(kAudioFormatAppleIMA4);
// // 音頻采樣率-->采樣頻率是指計算機每秒鐘采集多少個聲音樣本,是描述聲音文件的音質、音調,衡量聲卡、聲音文件的質量標準
// setting[AVSampleRateKey] = @(8000.0);
// // 音頻通道數-->iPhone只有一個 電腦可能多個
// setting[AVNumberOfChannelsKey] = @(1);
// // 線性音頻的位深度(8/16/24/32 bit) 數值越高 失真越小
// setting[AVLinearPCMBitDepthKey] = @(8);
直接傳一個空字典也是可以的,使用系統默認的參數
參考:
蘋果官方文檔
iOS開發系列--音頻播放、錄音、視頻播放、拍照、視頻錄制
iOS 播放音頻的幾種方法
iOS音頻播放(二):AudioSession
iOS音頻播放(二):AudioSession