Ben Spector
Ben Spector

Reputation: 329

Can't load AKAudioFile into AKSampler

I'm trying to use AKSampler on a simple iOS project to load a file and play it when tapping the device's screen.
I did the same steps with AKSamplePlayer and it worked fine, But I rather use the AKSampler, and also I get a strong feeling of missing something. I've tried the play() method, and also the one with the midi note.
Which one is right? Do they both work?Besides, AudioKit looks so promising.

Here is my code:

import UIKit
import AudioKit

class ViewController: UIViewController
{
    var sampler = AKSampler()
    var tapRecognizer = UITapGestureRecognizer()

    override func viewDidLoad()
    {


    super.viewDidLoad()
        do
        {
            let file = try AKAudioFile(readFileName: "AH_G2.wav")
            try sampler.loadAudioFile(file)
        }
        catch
        {
            print("No Such File...")
        }

        view.addGestureRecognizer(tapRecognizer)
        view.isUserInteractionEnabled = true
        tapRecognizer.addTarget(self, action: #selector(viewTapped))


        AudioKit.output = sampler
        AudioKit.start()
    }

    @objc private func viewTapped()
    {
        sampler.play(noteNumber: 60, velocity: 80, channel: 0)

        print("tapped...")
    }
}

Edit: My problem is actually with the loadAudioFile method, the AKAudioFile itself is good, and the AKSampler plays a default sine sound.
I tried also the AKAudioFile methods for creating player and sampler didn't.

let file = try AKAudioFile (readFileName: "AH_G2.wav")
player = file.player
sampler = file.sampler

I also tried to add the wav file using the menu, no change.

Upvotes: 2

Views: 420

Answers (2)

Ben Spector
Ben Spector

Reputation: 329

I've tried a different audio file and it worked fine. The first file was a mono file, so my conclusion here is that the AKSampler does not support mono files. Would love to hear more on that.

Upvotes: 1

c_booth
c_booth

Reputation: 2225

If you look at the implementation, there is just the one play() method, but it has default values for noteNumber, velocity, and channel:

@objc open func play(noteNumber: MIDINoteNumber = 60,
                         velocity: MIDIVelocity = 127,
                         channel: MIDIChannel = 0) {
        samplerUnit.startNote(noteNumber, withVelocity: velocity, onChannel: channel)
    }

Changing the MIDI note will change the pitch/speed of the sample playback (60 is standard, 72 is double speed, 48 would be half speed etc), and changing the velocity will change the volume.

NB: the title of your post is 'AKSampler doesn't play', but I ran your code (changing the sample, of course) and it played just fine on my iPad.

Upvotes: 1

Related Questions