如何连续检查AVAudioplayer是否在Swift中播放?

时间:2015-09-28 22:15:31

标签: ios swift audio

我制作了一个播放音频的简单应用。现在我想在播放音频时自动将“暂停”按钮更改为“播放”。我该如何检查? 这是代码:

echo "Message: " . $data->user_msg . "<br/>";

最后一个if语句应该在函数内部,但是我如何(连续)调用该函数?

2 个答案:

答案 0 :(得分:4)

您不必不断检查 - 您应该在View Controller中实现AVAudioPlayerDelegate协议:https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVAudioPlayerDelegateProtocolReference/index.html#//apple_ref/occ/intfm/AVAudioPlayerDelegate/audioPlayerDidFinishPlaying:successfully

请参阅:audioPlayerDidFinishPlaying:successfully:。我认为你会发现它与你想做的完全相反,这实际上是正确的方法。这样,您的播放器只需拨打&#34; end&#34;你定义的功能。

答案 1 :(得分:0)

这么多重复的问题......这是我的重复答案:

import UIKit
import AVFoundation
import MediaPlayer


class ViewController: UIViewController,AVAudioPlayerDelegate {

    var player: AVAudioPlayer = AVAudioPlayer()

    @IBAction func play(_ sender: UIButton) {
        player.play()
        player.currentTime=14*60-10
        print(player.currentTime)
    }
    @IBAction func pause(_ sender: UIButton) {
        player.pause()
    }
    @IBAction func replay(_ sender: UIButton) {
        player.currentTime=0
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        do{
            let audioPath = Bundle.main.path(forResource: "elon", ofType: "mp3")
            player = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: audioPath!))
            player.prepareToPlay()
            player.delegate = self
        }
        catch{
            print(error)
        }
    }

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool){
        print(flag)
        print("here")
        if flag == true{

        }
    }


}