如何在 SwiftUI 中等待音频完成?
Posted
技术标签:
【中文标题】如何在 SwiftUI 中等待音频完成?【英文标题】:How to wait for the completion of the audio in SwiftUI? 【发布时间】:2020-06-18 17:32:10 【问题描述】:我只想等到声音结束并调用下一个声音......
这是ConentView struct
中的主要功能,我用处理程序播放声音:
func askNew()
self.isPlaying = true
playQuestion
//1st audio
askNew
//2nd audio to play
//Change the global @State to see the result
self.isPlaying = false
播放声音的小功能。显然,它们仅在音频会话开始时才通知我们,而不是等待结束。
// MARK: - Question
func playQuestion(finished: () -> Void)
GSAudio.sharedInstance.playSound(sound: "question", type: "mp3", loop: false)
finished()
func askNewSetCurrent(finished: () -> Void)
GSAudio.sharedInstance.playSound(sound: "next_sound", type: "mp3", loop: false)
finished()
【问题讨论】:
***.com/help/minimal-reproducible-example @Chris 变小了。我想无论如何都会有人要求显示播放器类。 【参考方案1】:试着这样想
import AVFoundation
class SwiftUIViewModel: NSObject, ObservableObject
private var avPlayer: AVAudioPlayer!
private var arrayOfAllTracks = [Track]()
// call play track from view
func playTrack()
self.play(track: arrayOfAllTracks[0])
private func play(track: Track)
self.avPlayer = try! AVAudioPlayer(contentsOf: track.url, fileTypeHint: AVFileType.mp3.rawValue)
self.avPlayer?.delegate = self
avPlayer.play()
private func playNext()
let track = self.arrayOfAllTracks[1]
self.play(track: track)
extension SwiftUIViewModel: AVAudioPlayerDelegate
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool)
guard flag else return
self.playNext()
struct Track
let url: URL!
【讨论】:
以上是关于如何在 SwiftUI 中等待音频完成?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 SwiftUI 中使用 .fileimporter 保存音频文件并检索文件并在 SwiftUI 列表中显示它们的文件名?