ios - Swift - 停止 avaudioplayer

标签 ios swift avfoundation avaudioplayer

我正在尝试将音板构建到应用程序中,并找到了一种使用标签来控制播放声音的有效方法。不过,我现在正在尝试集成一个可以与 AVAudioPlayer 上的 .stop() 方法一起使用的暂停按钮,但是我当前的代码出现错误:

EXC_BAD_ACCESS

这就是我现在正在使用的,有什么想法吗?

import UIKit
import AVFoundation

let soundFilenames = ["sound","sound2","sound3"]
var audioPlayers = [AVAudioPlayer]()

class SecondViewController: UIViewController {

     var audioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

     for sound in soundFilenames {
          do {
               let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(sound, ofType: "mp3")!)
               let audioPlayer = try AVAudioPlayer(contentsOfURL: url)
               audioPlayers.append(audioPlayer)
          } catch {
               //Catch error thrown
               audioPlayers.append(AVAudioPlayer())
          }
     }
     }


     @IBAction func buttonPressed(sender: UIButton) {
          let audioPlayer = audioPlayers[sender.tag]
          audioPlayer.play()
     }
     @IBAction func stop(sender: UIButton) {
          audioPlayer.stop()
     }

}

最佳答案

停止功能中的audioPlayer不是播放器。您应该在buttonPressed函数中分配它。

@IBAction func buttonPressed(sender: UIButton) {
      audioPlayer = audioPlayers[sender.tag]
      audioPlayer.play()
 }

顺便说一句,您可以将audioPlayer标记为“?”属性,初始化此Controller时会更高效。

class SecondViewController: UIViewController {

     var audioPlayer: AVAudioPlayer?

     let enableMuiltPlayers = false
....


    @IBAction func buttonPressed(sender: UIButton) {
          if sender.tag < audioPlayers.count else {
               print("out of range")
               return
          }
          if enableMuiltPlayers {
             audioPlayers[sender.tag].play()
          } else {
             audioPlayer?.stop()
             //set the current playing player
             audioPlayer = audioPlayers[sender.tag]
             audioPlayer?.play()
          }
     }

     @IBAction func stop(sender: UIButton) {
          let wantToStopAll = false
          if enableMuiltPlayers  && wantToStopAll {
              stopAll()
          } else {
              audioPlayer?.stop()
          }
          audioPlayer = nil
     }
}

停止所有:

fun stopAll() {
    for player in audioPlayers {
        player.stop()
    }
}

关于ios - Swift - 停止 avaudioplayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38409834/

相关文章:

swift - 是否可以通过在 iOS 中使用具有质量设置的 jpeg 编码器来记录并保存到文件?

ios - 快速核心数据

ios - 如何从 NSArray 输出中删除新行

ios - 容器 View Controller addSubview 异常

iphone - 如果使用全屏,则无法在 MoviePlayer 中看到按钮

ios - 在 Xcode 中打印输出时出错(swift)

ios - 如何根据Firestore数据在collectionView中显示行和节标题?

ios - 在 Swift SpriteKit 项目中播放声音?

ios - 使用 AVFoundation AVPlayer 循环播放视频?

ios - 为什么AVAudioPlayer无法播放?