单击按钮时会产生随机声音迅速4

时间:2018-07-27 14:22:45

标签: ios swift

我有一个从sound1.wav,sound2.wav,sound3.wav ....到sound20.wav的.wav文件列表。

我想在用户触摸按钮时播放随机声音。我应该使用什么方法以及如何使用?

3 个答案:

答案 0 :(得分:0)

每当用户按下按钮时,运行以下代码:

在Swift 4.2中,它非常简单:

let randIndex = Int(arc4random_uniform(20)) // Random number between 0 and 20
let sound = arrayOfSounds[randIndex]

在早期版本中:

model.most_similar('word')

然后使用AVAudioPlayer或您想要的任何其他方法(如正在制作游戏的SpriteKit)播放声音。

答案 1 :(得分:0)

您可以使用arc4random_uniform()和AudioServicesPlaySystemSound()方法来实现所需的功能。

首先,您需要import AudioToolbox

制作一个函数来生成声音并在@IBAction函数内部调用它

这就是您的操作方式:

@IBAction func buttonPressed(_ sender: UIButton){
    playSound() //calling the function
}

    func playSound(){
    //select random number i.e sound1,sound2,sound3...sound[n]
    let randomNumber = Int(arc4random_uniform(TotalSoundFiles))
    //create the sound
    if let soundURL = Bundle.main.url(forResource: "sound\(randomNumber + 1)", withExtension: ".wav"){
        var mySound: SystemSoundID = 0
        AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
        //Play the sound
        AudioServicesPlaySystemSound(mySound)
    }
}

答案 2 :(得分:0)

这是一个简单的解决方案:按下按钮时调用的playSound()函数

import Foundation
import AVFoundation

var player: AVAudioPlayer?

func playSound() {
    //generate a random Int between 0 and 19, and then add 1
    let random = Int(arc4random_uniform(20)) + 1
    //Construct the sound file name
    let randomSoundName = "sound" + String(random) + ".wav"

    //Then check that the file is in the app bundle
    guard let url = Bundle.main.url(forResource: randomSoundName, withExtension: "wav") else { return }

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)



        /* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
        player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue)

        /* iOS 10 and earlier require the following line:
         player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeWAVE) */

        guard let player = player else { return }

        player.play()

    } catch let error {
        print(error.localizedDescription)
    }
}