简体   繁体   English

首次音频启动延迟-iOS Swift

[英]Audio Start Delay For The First Time - ios Swift

I am creating an application with five buttons. 我正在创建一个带有五个按钮的应用程序。 When I click on each button each audio will play. 当我单击每个按钮时,将播放每个音频。 It is working. 这是工作。 Now my problem is when I click first button audio play with 1 second delay(App stuck for 1 second) and play. 现在我的问题是,当我单击具有1秒延迟(应用程序停留1秒)的第一按钮音频播放并播放时。 Next time clicks a button audio play without any delay. 下次单击按钮时,音频播放将没有任何延迟。 What could be the issue here? 这里可能是什么问题?

I am using the following code to play an audio 我正在使用以下代码播放音频

var currentAudio = try? AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sample_audio", ofType: "mp3")!));
 currentAudio!.stop()
currentAudio!.currentTime = 0
 currentAudio!.play();

Please someone help me to finds this issue. 请有人帮我找到这个问题。

You could use AVAudioPlayer's .prepareToPlay() method to preload the player's buffers , it will increase AVAudioPlayer's performance (faster start). 您可以使用AVAudioPlayer的.prepareToPlay()方法来预加载播放器的缓冲区 ,这将提高AVAudioPlayer的性能(更快启动)。

The idea is to prepare the player some time before actually playing it: 这个想法是在实际玩游戏之前准备一些时间:

currentAudio?.prepareToPlay()

then later, in your play function, it will start immediately: 然后稍后,在您的播放功能中,它将立即开始:

currentAudio?.play()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM