简体   繁体   中英

Sequential sound upon dragging

I've built a small Xylophone app for iPhone, which has 7 buttons, each playing its own note when touched. I want to expand its functionality, so that when a user drags their finger from top button to bottom most or other way round, all notes are played sequentially, just as they would if you dragged your finger across piano keys.

在此处输入图片说明

I've experimented with adding various drag gestures (inside/outside, enter/exit), but they all work with only first button that receives an action. Ie the first sound is played when a finger is dragged outside of the first button, but when it enters the second button then nothing happens.

I was trying to connect different gestures (Touch Up Inside + Drag) into this single IBAction:

@IBAction func notePressed(_ sender: UIButton) {

    playNote(noteNumber: sender.tag)

}

func playNote(noteNumber : Int) {
    let soundURL = Bundle.main.url(forResource: "note\(noteNumber)", withExtension: "wav")

    do {
        try audioPlayer = AVAudioPlayer.init(contentsOf: soundURL!)
    } catch {
        print(error)
    }

    audioPlayer.play()
}

Maybe separate IBActions should be created? Can anyone give me a hint on where I should be looking?

Here how I worked it around:

  • Expand the ViewController class. Check the panView.swift file. Here you'll create the event catcher to listen for the Swipe Gesture Recognizer (That you need to add previously into your main storyboard)
  • Create an array of AVAudioPlaye objects. Initialize those objects with the path URL and then se them ready to play. See the prepareSounds() function.

More detailed explanation here

Let me know if you have any trouble recreating the app on your end.

Cheer!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM