在播放第二个声音时,先暂停第一个声音,等第二个声音播放完毕后,再恢复第一个声音的播放。
具体代码如下:
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate {
var player1: AVAudioPlayer!
var player2: AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
// 创建player1和player2
let path1 = Bundle.main.path(forResource: "sound1", ofType: "mp3")
let url1 = NSURL.fileURL(withPath: path1!)
let path2 = Bundle.main.path(forResource: "sound2", ofType: "mp3")
let url2 = NSURL.fileURL(withPath: path2!)
do {
player1 = try AVAudioPlayer(contentsOf: url1)
player1.delegate = self
player1.prepareToPlay()
player2 = try AVAudioPlayer(contentsOf: url2)
player2.delegate = self
player2.prepareToPlay()
} catch let error as NSError {
print(error.description)
}
}
func playSound1() {
player1.play()
}
func playSound2() {
player1.pause()
player2.play()
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
if player == player2 {
player1.play()
}
}
}