EssamSoft
EssamSoft

Reputation: 725

Play sound with AKAudioPlayer - iOS

How to declare AKAudioPlayer?

I'm using AudioKit Lib and I just need help to play .wav file with change file button.

    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()

            }

        }

Upvotes: 2

Views: 3107

Answers (2)

EssamSoft
EssamSoft

Reputation: 725

take look on AudioKit playground

update

AKAudioPlayer is deprecated, use AudioPlayer insted and check AudioKit v5 Migration Guide

Upvotes: 1

Abdullah Ayyash
Abdullah Ayyash

Reputation: 59

This is a very fast solution to your problem. It can be done better but at least you can get the idea.

First try to make a new class with a function to play your file and then another function to reload your new replacement file like this.

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()
  }
}

Initiate the class inside your view

class testViewController: UIViewController {

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

Play your music inside your view

override func viewDidLoad() {
    super.viewDidLoad()

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

}

Then when you want to reload a new file use the rePlay function

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

}

Upvotes: 2

Related Questions