创建一个随机音频声音发生器

时间:2016-08-11 03:40:45

标签: ios swift audio random

感谢您的回复。

当我按一次按钮时,我正在尝试制作一个程序,会播放两个随机声音。如果我按下按钮,我可以播放随机声音,但我看到如果按下按钮,随机声音每次都会以不同的方式播放。

我可以将声音粘贴在一起,按照我想要的顺序听到它们,但我想快速生成声音。

我想到了AVqueplayer将其作为播放列表。我以为这可以像一对骰子一样比喻。例如,如果我要掷骰子,就会发出随机声音。

我仍然是一个新手,并试图自己解决这个问题,因为它看起来很简单,但我现在没有选择。

这是我到目前为止所得到的。每当我按下按钮时,这将发出随机声音。

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var player: AVAudioPlayer = AVAudioPlayer()

    var sounds = ["sound1", "sound2", "sound3"]

    override func viewDidLoad() {
        super.viewDidLoad()  

    }

    override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
        if event!.subtype == UIEventSubtype.motionShake {


            let randomNumber = Int(arc4random_uniform(UInt32(sounds.count)))
            let fileLocation = Bundle.main.path(forResource: sounds[randomNumber], ofType: "mp3")
            var error: NSError? = nil
            do { try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileLocation!))
            player.play()
            } catch {}           
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

1 个答案:

答案 0 :(得分:0)

使用相同的代码,并添加具有匹配文件位置的第二个随机数将允许声音重复播放,两者都是随机的:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var player: AVAudioPlayer = AVAudioPlayer()

    var sounds = ["sound1", "sound2", "sound3"]

    override func viewDidLoad() {
        super.viewDidLoad()  

    }

    override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
        if event!.subtype == UIEventSubtype.motionShake {


            let randomNumber1 = Int(arc4random_uniform(UInt32(sounds.count)))
            let randomNumber2 = Int(arc4random_uniform(UInt32(sounds.count)))
            let fileLocation1 = Bundle.main.path(forResource: sounds[randomNumber1], ofType: "mp3")
            let fileLocation2 = Bundle.main.path(forResource: sounds[randomNumber2], ofType: "mp3")
            //var error: NSError? = nil
            do {
                try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileLocation1!))
                player.play()
                try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileLocation2!))
                player.play()
            } catch {}           
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
相关问题