我正在尝试按一个按钮,然后音频文件一个接一个地播放。
下面是我的代码。我按下播放按钮,两种声音同时播放。
我试图按下播放按钮,声音开始和停止,然后另一个声音文件开始和停止。我的目标是按下一个按钮来按下 2 个声音文件。谢谢
我正在循环尝试,但它不起作用。
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var sliderValue: UISlider!
var player:AVAudioPlayer = AVAudioPlayer()
var player1:AVAudioPlayer = AVAudioPlayer()
@IBAction func play(_ sender: AnyObject) {
player.play()
player1.play()
}
@IBAction func pause(_ sender: AnyObject) {
player.pause()
}
@IBAction func stop(_ sender: AnyObject) {
player.stop()
player.currentTime = 0
}
@IBAction func sliderChanged(_ sender: AnyObject) {
player.volume = sliderValue.value
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let audioPath = Bundle.main.path(forResource: "sound1", ofType: "mp3")!
let audioPath1 = Bundle.main.path(forResource: "sound2", ofType: "mp3")!
do {
try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioPath))
try player1 = AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioPath1))
} catch{
//Process Error here
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Best Answer-推荐答案 strong>
当然不能循环执行!
依次播放声音文件的正确方法是使用AVAudioPlayerDelegate 。
在您的 View Controller 中,遵守 AVAudioPlayerDelegate :
class YourViewController: UIViewController, AVAudioPlayerDelegate {
// ...
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer,
successfully flag: Bool) {
}
}
如您所见,我在 Controller 中添加了一个 audioPlayerDidFinishPlaying 方法。
所以你想先玩player ,然后player1 ,对吧?
在viewDidLoad 中,添加这一行:
player.delegate = self
并且在我刚刚添加的方法中,写:
player1.play()
其他的IBAction方法应该稍微改变一下:
@IBAction func play(_ sender: AnyObject) {
player.play()
}
@IBAction func pause(_ sender: AnyObject) {
if player.isPlaying {
player.pause()
} else if player1.isPlaying {
player1.pause()
}
}
@IBAction func stop(_ sender: AnyObject) {
if player.isPlaying {
player.stop()
} else if player1.isPlaying {
player1.stop()
}
}
@IBAction func sliderChanged(_ sender: AnyObject) {
player.volume = sliderValue.value
player1.volume = sliderValue.value
}
关于ios - 尝试按一个按钮然后按顺序或随机播放音频,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/38911399/
|