尝试按一个按钮,然后按顺序或随机播放音频

时间:2016-08-12 06:34:01

标签: ios swift avaudioplayer

我试图按一个按钮,音频文件一个接一个地播放。

以下是我的代码。我按下播放按钮,两个声音同时播放。 我试图按下播放按钮,声音开始和停止,然后另一个声音文件开始和停止。按下一个按钮可以按下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.
    }
}

2 个答案:

答案 0 :(得分:0)

当然,你不能在循环中做到这一点!

播放声音文件的正确方法是使用AVAudioPlayerDelegate

在视图控制器中,符合AVAudioPlayerDelegate

class YourViewController: UIViewController, AVAudioPlayerDelegate {
    // ...
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer,
                         successfully flag: Bool) {

    }
}

如您所见,我向控制器添加了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
}

答案 1 :(得分:0)

如果您还可以使用其他对象AVQueuePlayer进行管理,则可以找到文档herehere指南。