AVFoundation
initializing
let file = NSBundle.mainBundle().pathForResource("audio", ofType: "mp3")
let url = NSURL(fileURLWithPath: file!)
do{
self.audioPlayer = try AVAudioPlayer(contentsOfURL: url)
}catch let error as NSError {
print(error.description)
}
other function
– initWithData:error:
– initWithData:fileTypeHint:error:
– initWithContentsOfURL:fileTypeHint:error:
Controlling Function
function play() -> Bool
function pause()
function stop()
function prepareToPlay() -> Bool
A Boolean value that indicates whether the audio player is playing(YES) or not(NO). (read-only)
var playing: Bool {get}
var volume:Float // ranging from 0.0 through 1.0 on a linear scale
setting background play
https://developer.apple.com/library/ios/qa/qa1668/_index.html
往plist文件加个 key="Required background modes" item 0 = "App plays audio or streams audio/video using AirPlay"
code
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
}catch let error as NSError {print(error.description)}
引用
(http://coderzhang.xyz/2016/04/02/%E4%BD%BF%E7%94%A8avaudioplayer%E6%92%AD%E6%94%BE%E9%9F%B3%E9%A2%91/)
''prepareToPlay方法会取得需要的音频硬件并预加载到Audio Queue的缓冲区,这样可以降低play方法调用后准备播放产生的延时.prepareToPlay方法如果没有被手动显式调用,那么当调用play方法时会隐式调用.''
volume:播放器的音量独立于系统音量,可以通过对播放器音量的处理实现很多有趣的效果,比如声音的渐隐效果
pan:允许使用立体声播放,范围从-1.0(极左)到1.0(极右),默认为0,居中
rate:iOS 5以后允许用户在不改变音调的情况下调整播放速率,范围从0.5(半速)到2.0(2倍速)
numberOfLoops:可以设置播放器循环播放次数,设置为-1则表示无限循环