当声音在 swift 中播放完毕时如何执行功能



我正在构建一个声音测验应用程序,该应用程序要求用户从多个声音选项中猜测正确的声音。我想知道是否有任何功能可以在声音播放完毕时执行动作,例如 AVAudioPlayer .isplay 或 .stop。

我认为这就是您正在寻找的

struct Manager
{    
//Required Objects - AVFoundation
///AVAudio Session
static var recordingSession: AVAudioSession!
///AVAudio Recorder
static var recorder: AVAudioRecorder?
///AVAudio Player
static var player: AVAudioPlayer?
}

播放音乐

//Set player with audio File
do
{
try Manager.player = AVAudioPlayer.init(contentsOf: returnPathAtSelectedIndex(fileName: fileName))
//Set required delegates and Values
Manager.player?.delegate = self
Manager.player?.volume = 1.0
Manager.player?.prepareToPlay()
Manager.player?.play()
}
catch
{
print("Error while playing music: (error.localizedDescription)")
}

音频播放器代表

//MARK:- Audio Player Delegates
extension RecordingManager: AVAudioPlayerDelegate
{
//MARK: Audio Player Finishes Playing audio
/**
Called when a sound has finished playing.
- parameter player: player instance
- parameter flag: Bool player is running or not successfully
*/
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool)
{
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "StoppedPlaying"), object: nil)
player.stop()
Manager.player?.stop()
Manager.recordingalreadyPlayedStatus = false
print("Finish Playing")
}
//MARK: Audio Player error occur while Playing
/**
Called when an audio player encounters a decoding error during playback.
- parameter player: player instance
- parameter error: Error if occurs
*/
func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer,error: Error?)
{
print("Encoding Error: (String(describing: error?.localizedDescription))")
}
}

func audioPlayerDidFinishPlay ? https://developer.apple.com/documentation/avfoundation/avaudioplayerdelegate/1389160-audioplayerdidfinishplaying

创建您的AVAudioPlayer

将自己设置为玩家的代表。

实现audioPlayerDidFinishPlaying(_:successfully:)委托方法。当声音播放完毕时,它会被调用

有关详细信息,请参阅有关AVAudioPlayerAVAudioPlayerDelegate协议和audioPlayerDidFinishPlaying(_:successfully:)委托方法的文档。

最新更新