iOS开发Swift-4-IBAction,group,音乐播放器-木琴App

1.使用素材创建木琴App的UI。

2.连接IBAction。

其余按钮直接拖拽到play里边。

当鼠标置于1处时2处显示如图,表示成功。当用户按下任一按钮都会触发play中的内容。

3.将7个按钮的View中的Tag值分别调为1、2、3、4、5、6、7.

4.将音频文件拖入项目文件中。

Create groups时,实际上系统只创建了一个group而不是真实文件夹。所以在填写此group下文件的路径时不需要加上group名/ 。而Create folder references需要加文件名/ 。在文件中创建新的文件夹(group)后同样不需要加上group名/ 。

5.在ViewController中编写代码。

复制代码
import UIKit
import AVFoundation

class ViewController: UIViewController {
    var player: AVAudioPlayer!
    let sounds = ["note1", "note2", "note3", "note4", "note5", "note6", "note7"]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

    @IBAction func play(_ sender: UIButton) {
        play(sender.tag)
    }
    
    func play(_ tag: Int) {  //play方法重载
        //forResource:音频文件名。withExtension:扩展名
        let url = Bundle.main.url(forResource: sounds[tag - 1], withExtension: "wav")!
        do {
            player = try AVAudioPlayer(contentsOf: url)
            player.play()
        } catch {
            print(error)
        }
    }
    
}

6.启动测试

点击不同按键可以发出不同音符的音乐。

相关推荐
水木姚姚11 小时前
初识C++
开发语言·c++
权泽谦11 小时前
新世代的 C++:当 ChatGPT 遇上模板元编程
开发语言·c++·chatgpt
MediaTea11 小时前
Python 第三方库:Flask(轻量级 Web 框架)
开发语言·前端·后端·python·flask
2501_9411114011 小时前
C++中的状态模式实战
开发语言·c++·算法
Dxxyyyy12 小时前
零基础学JAVA--Day34(Map接口+HashTable+HashMap+TreeSet+TreeMap+开发中如何选择集合实现类?(重要))
java·开发语言
rainFFrain12 小时前
qt显示类控件---QProgressBar
开发语言·qt
rainFFrain12 小时前
qt输入类控件---QComboBox/QSpinBox
开发语言·qt
2501_9411118912 小时前
低延迟系统C++优化
开发语言·c++·算法
未来之窗软件服务13 小时前
自建开发工具IDE(二)文件托拽读取——东方仙盟炼气期
开发语言·前端·javascript·仙盟创梦ide·东方仙盟
Hello_WOAIAI13 小时前
4.2 python多线程编程:threading 模块深度解析
开发语言·python