【发布时间】:2018-12-06 22:34:38
【问题描述】:
我正在构建一个声音测验应用程序,要求用户从多个声音选项中猜出正确的声音。我想知道是否有任何功能可以在声音播放完毕时执行操作,例如 AVAudioPlayer .isplaying 或 .stop。
【问题讨论】:
标签: ios swift avaudioplayer
我正在构建一个声音测验应用程序,要求用户从多个声音选项中猜出正确的声音。我想知道是否有任何功能可以在声音播放完毕时执行操作,例如 AVAudioPlayer .isplaying 或 .stop。
【问题讨论】:
标签: ios swift avaudioplayer
我想这就是你要找的东西
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))")
}
}
【讨论】:
创建您的AVAudioPlayer
将自己设置为玩家的代表。
实现audioPlayerDidFinishPlaying(_:successfully:) 委托方法。声音播放完毕后会调用它
有关更多信息,请参阅有关 AVAudioPlayer、AVAudioPlayerDelegate 协议和 audioPlayerDidFinishPlaying(_:successfully:) 委托方法的文档。
【讨论】:
func audioPlayerDidFinishPlaying ? https://developer.apple.com/documentation/avfoundation/avaudioplayerdelegate/1389160-audioplayerdidfinishplaying
【讨论】: