4

在 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

}
4

2 回答 2

5

您每次在播放按钮操作时都在初始化 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() 
}
于 2016-03-08T10:47:34.157 回答
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)
    }
}
于 2016-04-24T13:14:02.230 回答