用字符swift解码莫尔斯电码

用字符swift解码莫尔斯电码,swift,avfoundation,swift-playground,morse-code,Swift,Avfoundation,Swift Playground,Morse Code,我想在一个快速的操场上做一个摩尔斯电码转换器。我得到了转换工作,但我需要使代码“说话”与AVFoundation。我如何解码莫尔斯电码字符串,使其在每个“.”时播放短嘟嘟声,在每个“-”时播放长嘟嘟声 以下是我目前的代码: func speakTheCode(message: String) { var speaker = AVAudioPlayer() let longBeep = URL(fileURLWithPath: Bundle.main.path(forResour

我想在一个快速的操场上做一个摩尔斯电码转换器。我得到了转换工作,但我需要使代码“说话”与AVFoundation。我如何解码莫尔斯电码字符串,使其在每个“.”时播放短嘟嘟声,在每个“-”时播放长嘟嘟声

以下是我目前的代码:

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

试着把字符串解码成相应的音频

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: "..--..")

为什么
speaker
声明在循环之外?为什么要创建一个一次性的
AVAudioPlayer()
?并且对
play()
的调用不会被阻止。循环将运行得非常快,启动几个音频播放器的并发实例。我的错误,我只是以源代码为例,我更新了我的答案。它应该是一个播放序列。现在代码有问题。。。当我按下转换键时,操场崩溃了。没有构建时错误,只有运行时错误。这和音频的URL有关吗?我在iPad上的swift playgrounds应用程序中实现了这一点,但我不确定这与内置Xcode相比如何