如何在avaudionode swift中播放歌曲的特定时间

时间:2019-07-04 09:38:32

标签: ios swift avfoundation avaudioplayer avaudioplayernode

我制作了一个简单的mp3播放器,该播放器具有播放,暂停和停止特定歌曲的功能。在后台模式下播放的歌曲意味着当我将播放器屏幕更改为连续播放的另一首屏幕歌曲时,如何在当前时间连续播放歌曲。但实际上它是从起点重新开始的。

代码:

import UIKit
import AVFoundation
import CoreMotion
import MediaPlayer
import Foundation

class ViewController: UIViewController {

var audioEngine = AVAudioEngine()
var playerNode = AVAudioPlayerNode()
let timeShift = AVAudioUnitTimePitch()

override func viewDidLoad() {
    super.viewDidLoad()

    audioEngine.inputNode.reset()
    if playerNode.engine == nil {
        audioEngine.attach(playerNode)
        audioEngine.attach(timeShift)
    }
    audioEngine.connect(playerNode, to: timeShift, format: nil)
    audioEngine.connect(timeShift, to: audioEngine.mainMixerNode, format: nil)
    audioEngine.prepare()
    do {
        try audioEngine.start()
    } catch {
        print("Could not start audio engine")
    }

    do {
        try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.mixWithOthers, .allowAirPlay, .defaultToSpeaker])
        try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
        try AVAudioSession.sharedInstance().setActive(true)
    } catch {
        print(error)
    }

    let urlMain = Bundle.main.url(forResource: "Demo", withExtension: "mp3")!
    let audioAsset = AVURLAsset(url: urlMain, options: nil)
    let audioDuration = audioAsset.duration
    let audioDurationSeconds = CMTimeGetSeconds(audioDuration)
    print(audioDurationSeconds)
    do {
        let audioFile = try AVAudioFile(forReading: urlMain)
        playerNode.scheduleFile(audioFile, at: nil, completionHandler: nil)
        playerNode.play()
    }catch{
        print("No value")
        return
    }
}

@IBAction func pushToSecondVC(_ sender: UIButton) {
    self.dismiss(animated: true, completion: nil)
  }
}

0 个答案:

没有答案