[英]Auto play audio files in Swift
我正在制作一個非常簡單的應用程序,用戶可以在其中選擇要播放的音頻文件。 然后,他按下“播放”按鈕,它將一個接一個地播放所有選擇的文件。
為此,我創建了一個數組,用於存儲用戶想要播放的文件的名稱。 然后,由“播放”按鈕觸發的函數將對數組進行迭代,查找名稱並播放文件。
就像這樣:
//declaring the audioplayer
var audioPlayer = AVAudioPlayer()
//declaring the array
var selectedMusic = [String]()
該界面有6個按鈕,每個按鈕都鏈接到特定的音樂。 用戶可以通過點擊按鈕立即觸發音樂,或者長按選擇連續播放。 假設用戶得到選擇,並且數組將如下所示:
selectedMusic = ["Song 1", "Song 5", "Song 3", "Song 2"]
我播放歌曲的功能是:
for selection in selectedMusic {
if selection == "Song 1" {
guard let alertSound = Bundle.main.url(forResource: "Song 1", withExtension: "mp3") else {return}
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
audioPlayer = try AVAudioPlayer(contentsOf: alertSound)
audioPlayer.prepareToPlay()
audioPlayer.play()
} catch let error {
print(error.localizedDescription)
}
} else if selection == "Song 2" {
guard let alertSound = Bundle.main.url(forResource: "Song 2", withExtension: "mp3") else {return}
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
audioPlayer = try AVAudioPlayer(contentsOf: alertSound)
audioPlayer.prepareToPlay()
audioPlayer.play()
} catch let error {
print(error.localizedDescription)
}
等等,直到歌曲5。
我想要的是按特定順序(1至5)而不是用戶選擇的順序播放選定的歌曲(這很重要)。
但是,此功能並沒有提供預期的結果,它只是播放選擇的最后一項。
那么,我應該如何做呢? 數組不是這里的最佳選擇嗎? 正如我所提到的,按時間順序播放歌曲是必須的。
任何幫助將不勝感激:)謝謝!
好吧,首先,您使用for並在其中重復執行代碼。從理論上講,您可以
audioUrls.forEach { (url) in
guard let alertSound = Bundle.main.url(forResource: url, withExtension: "mp3") else {return}
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
audioPlayer = try AVAudioPlayer(contentsOf: alertSound)
audioPlayer.prepareToPlay()
audioPlayer.play()
} catch let error {
print(error.localizedDescription)
}
}
其次,您沒有跟蹤音頻,因此您的程序不知道軌道已完成播放,並且您正在用新對象覆蓋播放器。
例如,在下面的代碼中,我跟蹤我的音頻播放器並使用當前時間更新標簽。
func keepTrackOfAudio() {
audioPlayer?.addObserver(self, forKeyPath: "currentItem.loadedTimeRanges", options: .new, context: nil)
//track progress
let interval = CMTime(value: 1, timescale: 2)
audioPlayer?.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main , using: { (progressTime) in
let seconds = CMTimeGetSeconds(progressTime)
let secondsString = String(format: "%02d", Int(seconds.truncatingRemainder(dividingBy: 60)))
let minutesString = String(format: "%02d", Int(seconds / 60))
self.audioCurrentTimeLabel.text = "\(minutesString):\(secondsString)"
//lets move the slider thumb
if let duration = self.audioPlayer?.currentItem?.duration {
let durationSeconds = CMTimeGetSeconds(duration)
self.audioSlider.value = Float(seconds / durationSeconds)
}
})
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let duration = audioPlayer?.currentItem?.duration {
let seconds = CMTimeGetSeconds(duration)
let secondsText = String(format: "%02d", Int(seconds) % 60)
let minutesText = String(format: "%02d", Int(seconds) / 60)
audioLengthLabel.text = "\(minutesText):\(secondsText)"
}
}
}
您的作業是計算音頻何時到達末尾,然后再播放下一首曲目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.