gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:31:03 28 4
gpt4 key购买 nike

感谢您的回复。

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

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

想到用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.
}
}

最佳答案

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

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.
}
}

关于ios - 创建一个随机音频声音发生器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38886889/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com