Zha*_*rik 3 xcode avaudioplayer swift 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
}
Run Code Online (Sandbox Code Playgroud)
您每次在播放按钮操作上都在初始化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")
}
}
Run Code Online (Sandbox Code Playgroud)
您的播放按钮操作将仅包含大量代码
@IBAction func playButton(sender: AnyObject)
{
audioPlayer!.play()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1773 次 |
| 最近记录: |