前言:
iOS里面导入AVFoundation
包进行音频使用管理,调用AVAudioPlayer
对象进行音频操作。这里有个小方法,直接粘贴即可使用。
调用方法:
private func playAudio(forResource: String, ofType: String){
if let bundlePath = Bundle.main.path(forResource: forResource, ofType: ofType) {
let url = URL.init(fileURLWithPath: bundlePath)
do {
try audioPlayer = AVAudioPlayer(contentsOf: url)
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
} catch let error as NSError {
print("audioPlayer error \(error.localizedDescription)")
}
}
}
说明:在哪个监听或viewDidLoad()方法里面加载就行了。第一个参数为要播放的音频文件名,第二个是音频文件类型。例如这里有一首名为"Lover.mp3"的音乐。调用方法写为playAudio(forResource: "Lover", ofType: "mp3")
即可。
另外,调用该方法的前提是先创建好AVAudioPlayer对象,实现AVAudioPlayerDelegate协议,并且已经设置delegate。
全部代码:
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate{
var audioPlayer: AVAudioPlayer = AVAudioPlayer();
private func playAudio(forResource: String, ofType: String){
if let bundlePath = Bundle.main.path(forResource: forResource, ofType: ofType) {
let url = URL.init(fileURLWithPath: bundlePath)
do {
try audioPlayer = AVAudioPlayer(contentsOf: url)
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
} catch let error as NSError {
print("audioPlayer error \(error.localizedDescription)")
}
}
}
@IBAction func oneListener(_ sender: Any) {
// Play the audio instance.
self.audioPlayer.play()
}
@IBAction func twoListener(_ sender: Any) {
// Pause the audio instance that playing.
self.audioPlayer.pause()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
playAudio(forResource: "myTest", ofType: "mp3")
self.audioPlayer.delegate = self
}
}
注意事项:
经测试,该方法只可以播放“源格式音频”。什么叫“源格式音频”,就是指该音频一开始是什么格式,调用时其种类就要写什么格式;而不是假设一开始源格式为mp3,人为地直接把文件名强行改为wma格式,这是不行的;但如果说一开始是mp3,经过音频转码转为其它格式则是可以的。之前从某个网站下下来的音频就是打不开,转码后才能打开播放就是这个原因。