在AVAudioPlayer暂停后,歌曲不会继续在Swift上播放

时间:2016-03-08 09:26:53

标签: swift xcode avaudioplayer pause

在AVAudioPlayer暂停后,歌曲不会继续,在Swift上重新开始。问题是当我选择暂停按钮并再次选择播放按钮时它应该从启动开始。

import UIKit
import AVFoundation
class DetailViewController: UIViewController {

let musicArray:[String] = ["reamon", "sandman"]

var audioPlayer: AVAudioPlayer?

var songIndex:Int = 0

@IBAction func pauseButton(sender: AnyObject) {
    audioPlayer!.pause()

}

@IBAction func playButton(sender: AnyObject) {

    let mySound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(musicArray[songIndex], ofType: "mp3")!)

    do{
        audioPlayer = try AVAudioPlayer(contentsOfURL: mySound)
        audioPlayer!.prepareToPlay()
        audioPlayer!.play()
    } catch {
        print("Error getting the audio file")
    }

}

@IBOutlet weak var stopButtonOutlet: UIButton!

@IBAction func stopButton(sender: AnyObject) {
    audioPlayer!.stop()
    audioPlayer!.currentTime = 0
}

func playSongAtIndex(index: Int) {

    songIndex = index

}

2 个答案:

答案 0 :(得分:4)

你每次在你的播放按钮动作上初始化AVAudioPlayer尝试用其他方法初始化你的AVAudioPlayer,这只会调用一次这个

override func viewWillAppear(animated: Bool) 
{
        self .intiAudioPlayer()
}

func intiAudioPlayer() 
{

      let mySound = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource(musicArray[songIndex], ofType: "mp3")!)

    do
   {
        audioPlayer = try AVAudioPlayer(contentsOfURL: mySound)
        audioPlayer!.prepareToPlay()
    } 
    catch {
        print("Error getting the audio file")
    }
}

你的播放按钮动作只包含这么多代码

 @IBAction func playButton(sender: AnyObject) 
{
   audioPlayer!.play() 
}

答案 1 :(得分:2)

我做另一种方式。它是播放和暂停的一个按钮。

@IBAction func playPauseButton(sender: AnyObject) {

    if (player.playing == true) {
        player.stop()
        playPauseButtonOutlet.setImage(UIImage(named: "play.jpg"), forState: UIControlState.Normal)
    } else {
        player.play()
        playPauseButtonOutlet.setImage(UIImage(named: "pause.jpg"), forState: UIControlState.Normal)
    }
}