快速制作播放列表(开始下一首歌)

时间:2015-05-13 12:00:55

标签: ios swift avfoundation avaudioplayer playlist

我用AVFoundation在swift中创建了一个声音播放器。我正在尝试在播放歌曲结束时开始播放下一首歌曲。我试图实现这个代码

if (audioPlayer.currentTime >= audioPlayer.duration){
    var recentSong = songPlaylist[selectedSongNumber + 1]
    audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath:
            NSBundle.mainBundle().pathForResource(recentSong, ofType: "mp3")!), error: nil)
    audioPlayer.play()
}

但我无法实现此代码(我不知道在哪里实现它。)这是我的完整代码

import UIKit
import AVFoundation
import AVKit

public var audioPlayer = AVPlayer()
public var selectedSongNumber = Int()
public var songPlaylist:[String] = ["song1", "song2"]
public var recentSong = "song1"
let playImage = UIImage(named: "Play.png") as UIImage!
let pauseImage = UIImage(named: "Pause.png") as UIImage!

class FirstViewController: UIViewController {

@IBOutlet weak var musicSlider: UISlider!

@IBOutlet weak var PlayPause: UIButton!

var audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath:
    NSBundle.mainBundle().pathForResource(recentSong, ofType: "mp3")!), error: nil)

override func viewDidLoad() {
    super.viewDidLoad()

    musicSlider.maximumValue = Float(audioPlayer.duration)

    var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("updateMusicSlider"), userInfo: nil, repeats: true)


    if (audioPlayer.currentTime >= audioPlayer.duration){

        var recentSong = songPlaylist[selectedSongNumber + 1]

        audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath:
            NSBundle.mainBundle().pathForResource(recentSong, ofType: "mp3")!), error: nil)

        audioPlayer.play()

        }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}
@IBAction func PlayPauseButton(sender: AnyObject) {

    if (audioPlayer.playing == false){
        audioPlayer.play()
        PlayPause.setImage(pauseImage, forState: .Normal)
    }else{
        audioPlayer.pause()
        PlayPause.setImage(playImage, forState: .Normal)
    }
}

@IBAction func StopButton(sender: AnyObject) {
    audioPlayer.stop()
    audioPlayer.currentTime = 0
    PlayPause.setImage(playImage, forState: .Normal)
}

@IBAction func musicSliderAction(sender: UISlider) {
    audioPlayer.stop()
    audioPlayer.currentTime = NSTimeInterval(musicSlider.value)
    audioPlayer.play()

}

func updateMusicSlider(){

    musicSlider.value = Float(audioPlayer.currentTime)

}

}

3 个答案:

答案 0 :(得分:8)

我正在用不同的东西更新我的代码:

import UIKit
import AVFoundation

class ViewController: UIViewController, AVAudioPlayerDelegate {

    var counter = 0
    var song = ["1","2","3"]
    var player = AVAudioPlayer()

    @IBOutlet weak var musicSlider: UISlider!

    override func viewDidLoad() {
        super.viewDidLoad()
        musicSlider.value = 0.0
    }

    func updateMusicSlider(){

        musicSlider.value = Float(player.currentTime)
    }

    @IBAction func playSong(sender: AnyObject) {

        music()
    }
    @IBAction func sliderAction(sender: AnyObject) {

        player.stop()
        player.currentTime = NSTimeInterval(musicSlider.value)
        player.play()
    }

    func music(){

        var audioPath = NSBundle.mainBundle().pathForResource("\(song[counter])", ofType: "mp3")!
        var error : NSError? = nil
        player = AVAudioPlayer(contentsOfURL: NSURL(string: audioPath), error: &error)
        musicSlider.maximumValue = Float(player.duration)
        var timer = NSTimer.scheduledTimerWithTimeInterval(0.05, target: self, selector: Selector("updateMusicSlider"), userInfo: nil, repeats: true)
        player.delegate = self
        if error == nil {
            player.delegate = self
            player.prepareToPlay()
            player.play()
        }
    }

    func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool)
    {
        println("Called")
        if flag {
            counter++
        }

        if ((counter + 1) == song.count) {
            counter = 0
        }

        music()
    }

}

你可以这样做。

希望它会有所帮助,HERE是更多信息的示例项目。

答案 1 :(得分:1)

您需要实施AVAudioPlayerDelegate协议的方法:

optional func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer!, successfully flag: Bool)

Documentation link

在这里播放您的下一个音乐项目。

但我不建议,因为AVAudioPlayer一次只能播放一个项目。完成后,您需要再次使用其他音乐项目进行实例化。我建议你使用AVQueuePlayer。已给出详细答案here。希望它有所帮助!

答案 2 :(得分:0)

我用AVFoundation在swift中创建了一个声音播放器。我使用progressView为歌曲计时,然后当它达到0.98743时,它将自动更新到下一首歌曲,这是Github链接:https://github.com/ryan-wlr/MusicPlayerIOS

func updateProgressView() {
    if (progressView.progress > a.advanced(by: 0.98743)) {
        audioPlayerDidFinishPlayeing()
    }

    if audioPlayer.isPlaying {
        let progress = Float(audioPlayer.currentTime/audioPlayer.duration)
        progressView.setProgress(progress, animated: true)
    }
}