簡體   English   中英

如何播放音頻文件樣本

[英]How to play an audio file sample

好吧,我正在嘗試執行與iTunes類似的操作,不確定是否仍然相同。 當您單擊歌曲時,它會提供音頻文件的樣本。 這是我的代碼外觀。

在此處輸入圖片說明

音樂文件的長度約為2-3分鍾。 我的開始時間為42秒。 但是,歌曲結束了。 我正在嘗試將音頻文件制作為30秒的樣本。 因此,它應該從42秒開始,到1分12秒結束。

感謝您的幫助。

每次音頻樣本開始播放時,您都可以創建一個Timer對象,該對象將使播放器在給定的時間內停止播放。

var audioPlayer = AVAudioPlayer()
var timer: Timer?

func prepareMusic() {
    ....

    // Your code to start playing sample

    audioPlayer.currentTime = 42
    audioPlayer.play()

    // Here we are stopping previous timer if there was any, and creating new one for 30 seconds. It will make player stop.

    timer?.invalidate()
    timer = Timer(fire: Date.init(timeIntervalSinceNow: 30), interval: 0, repeats: false) { (timer) in 
        if self.audioPlayer.isPlaying {
            self.audioPlayer.stop()
        }
    }

    RunLoop.main.add(timer!, forMode: .defaultRunLoopMode)
}

func musicButton(sender: UIButton) {
    ....

    // If sample is stopped by user — stop timer as well

    if audioPlayer.isPlaying {
        audioPlayer.stop()
        timer?.invalidate()
    }
}

我能想到的還有另外一種情況-如果您隱藏/關閉視圖控制器,您可能還想停止該計時器。

override func viewWillDisappear(_ animated: Bool) {
    timer?.invalidate()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM