ios - 在 Xcode 中播放音效
问题描述
我在 Xcode 中创建了一个播放短音效的按钮。我无法在播放时重新触发按钮/声音。因此,我必须等到声音消失才能重复效果。我的意图是每次按下按钮时,声音效果都会开始播放,即使它仍在淡出。有谁知道如何实现这一目标?我正在使用 XCode 11.6。我的代码如下。提前谢谢了。
导入 UIKit 导入 AVFoundation
类视图控制器:UIViewController {
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "1", ofType: "mp3")!))
audioPlayer.prepareToPlay()
} catch {
print(error)
}
}
@IBAction func Play(_ sender: Any) {
audioPlayer.play()
}
}
解决方案
如果我理解正确,您想在播放声音时阻止再次播放,并在播放完毕后播放声音,这样您就可以根据是否播放声音做出条件(在您的按钮操作中尝试):
if audioPlayer.isPlaying(){
// your statement when sound is playing in other word nothing to do
}else{
// your statement when sound is not playing and you want to start play
audioPlayer.play()
}
https://developer.apple.com/documentation/avfoundation/avaudioplayer/1390139-isplaying
推荐阅读
- javascript - ReferenceError:在初始化之前无法访问“ws”
- java - Apache POI 检查颜色为绿色、红色、蓝色 java。颜色比较
- csv - Go 如何响应 csv 文件?
- php - 如何在 PHP 变量中使用符号加号并获得结果?
- ruby-on-rails - 即时发送/流式传输动态压缩包
- ms-access - Access 导航窗格仅显示几个查询
- android - 在主要活动中使用 setTheme 时 setDefaultNightMode 不起作用
- python - 在多个页面中搜索特定元素并单击使用 Python Selenium
- javascript - 加入和分组 Json Nodejs
- java - Java Spring Security @PostFilter 性能