-1

I am trying to make a morse code converter in a swift playground. I got the conversion to work, but I need to make the code "speak" with AVFoundation. How can I decode the morse code string to play the short beep for every '.' and the long beep for every '-'?

Here's my code so far:

func speakTheCode(message: String) {
    var speaker = AVAudioPlayer()

    let longBeep = URL(fileURLWithPath: Bundle.main.path(forResource: "beep_long", ofType: "mp3")!)
    let shortBeep = URL(fileURLWithPath: Bundle.main.path(forResource: "beep_short", ofType: "mp3")!)

    try! speaker = AVAudioPlayer(contentsOf: longBeep)
    try! speaker = AVAudioPlayer(contentsOf: shortBeep)

    speaker.prepareToPlay()
}
Jorge Casariego
  • 21,948
  • 6
  • 90
  • 97
Matt
  • 21
  • 2

1 Answers1

1

Just try to decode the string to the correspondingly audio.

func speakTheCode(message: String) {
    var audioItems: [AVPlayerItem] = []

    guard let longPath = Bundle.main.path(forResource: "beep_long", ofType: "mp3"),
    let shortPath = Bundle.main.path(forResource: "beep_short", ofType: "mp3") else {
        print("Path is not availabel")
        return
    }

    let longBeep = AVPlayerItem(url: URL(fileURLWithPath: longPath))
    let shortBeep = AVPlayerItem(url: URL(fileURLWithPath: shortPath))

    for character in message.characters {
        if character == Character("-") {
            audioItems.append(longBeep)
        } else if character == Character(".") {
            audioItems.append(shortBeep)
        }
    }

    let player = AVQueuePlayer(items: audioItems)
    player.play()

}

speakTheCode(message: "..--..")
Willjay
  • 6,381
  • 4
  • 33
  • 58
  • Why is `speaker` declared outside of the loop? Why create a throwaway instance of `AVAudioPlayer()`? – rmaddy Mar 28 '17 at 02:34
  • And the call to `play()` does not block. The loop will run really fast kicking off several concurrent instances of audio players. – rmaddy Mar 28 '17 at 02:35
  • my faults, I just take the origin code for example, I updated my answer. It should be a sequence of playeritems. – Willjay Mar 28 '17 at 02:40
  • Now there is a problem with the code... the playground crashes when I press convert. No build time errors, just runtime. – Matt Mar 28 '17 at 02:55
  • Is it something to do with the URL of the audio? I'm making this in the swift playgrounds app on my iPad and I'm not sure how that compares to inside Xcode – Matt Mar 28 '17 at 03:02
  • you can use `guard` to make sure whether the `path` is available or not. – Willjay Mar 28 '17 at 03:17