swift - 每次网络请求成功后如何播放声音?
问题描述
我想在每次网络请求成功后播放声音。我有一些对象要使用 for 循环发送到服务器。在每次迭代中,我都会向服务器发送一个请求,每个请求完成后,我想播放一个声音。
我试过这个:
for object in objects {
sendObjectToServer(object)
}
func playSound() {
let url = Bundle.main.url(forResource: "sound", withExtension: "mp3")!
let player = try! AVAudioPlayer(url)
player.play()
}
func sendObjectToServer(object: Object) {
URLSession.shared.dataTask(with url: object.url) {(data,response,error) in
DispatchQueue.main.async {
playSound() // doesn't play sound synchronously
}
}
}
解决方案
为什么要使用主线程进行与后台相关的操作。Dispatch.main.async
仅在代码中更新您的 UI :
在物理设备上试试这个(测试和工作)
import AVFoundation
for object in objects {
DispatchQueue.global(qos: .background).async {
sendObjectToServer(object)
}
}
var player: AVAudioPlayer?
func playSound() {
guard let url = Bundle.main.url(forResource: "sound", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
/* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
/* iOS 10 and earlier require the following line:
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
func sendObjectToServer(object: Object) {
URLSession.shared.dataTask(with url: object.url) {(data,response,error) in
// Custom Logic
playSound()
}
}
推荐阅读
- ionic-framework - Ionic Iframe 在打字时不断重新加载
- vbscript - 为什么此文件调用在 UFT 中作为语法错误返回?
- c++ - 将 qt listwidget 中的项目列表转换为单选按钮
- apache-spark - Spark:哪里不能正常工作
- vba - MS Access VBA:创建具有多个工作表的 Excel 工作簿
- python-3.x - 从较长视频的选定秒数生成新视频
- bash - 在 shell 输出上使用 grep 返回布尔值?
- java - Java:将 LocalDateTime 保存到 MySQL 会持续减去 7 小时
- django - 关系“django_session”不存在
- javascript - 如何调用组件内部的方法确实从 react.js 中的第 3 方库更新?