使用 AKAudioPlayer 播放声音 - iOS

Play sound with AKAudioPlayer - iOS

如何申报AKAudioPlayer?

我正在使用 AudioKit Lib,我只需要帮助来播放带有更改文件按钮的 .wav 文件。

    import UIKit
    import AudioKit

    class ViewController: UIViewController {

            let file   = NSBundle.mainBundle().pathForResource("song", ofType: "wav")
            let song  = AKAudioPlayer(file!) // <--- ERROR = instance member 'file' cannot be used on type 

            override func viewDidLoad() {
                super.viewDidLoad()

                AudioKit.output = song
                AudioKit.start()

                song.play()
            }


            @IBAction func btn(sender: AnyObject) {

                song.replaceFile("NewFile")
                song.play()

            }

        }

这是解决您的问题的一种非常快速的方法。它可以做得更好,但至少你可以理解。

首先尝试制作一个新的 class,其中包含播放您的文件的功能,然后是另一个重新加载您的新替换文件的功能。

class PlayMyMusic {
  var songFile = NSBundle.mainBundle()
  var player: AKAudioPlayer!

  func play(file: String, type: String) -> AKAudioPlayer {
    let song = songFile.pathForResource(file, ofType: type)
    player = AKAudioPlayer(song!)
    return player
  }

  func rePlay(file: String, type: String, curPlay: AKAudioPlayer) {
    let song = songFile.pathForResource(file, ofType: type)
    curPlay.stop()
    curPlay.replaceFile(song!)
    curPlay.play()
  }
}

在您的视图中启动 class

class testViewController: UIViewController {

   let doPlay = PlayMyMusic().play("A", type: "wav")
   .........
   .........

在您的视野中播放您的音乐

override func viewDidLoad() {
    super.viewDidLoad()

    AudioKit.output = self.doPlay
    AudioKit.start()
    doPlay.looping = true
    doPlay.play()

}

然后当你想重新加载一个新文件时使用重播功能

@IBAction func btn(sender: AnyObject) {
    PlayMyMusic().rePlay("C", type: "wav", curPlay: self.doPlay)

}

看看 AudioKit playground

更新

AKAudioPlayer 已弃用,请使用 AudioPlayer insted 并检查 AudioKit v5 Migration Guide