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.启动测试

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

相关推荐
Highcharts.js4 分钟前
缺失数据可视化图表开发实战|Highcharts创建人员出生统计面积图表示例
开发语言·前端·javascript·信息可视化·highcharts·图表开发
测试员周周5 小时前
【Appium 系列】第16节-WebView-H5上下文切换 — 混合应用的自动化难点
运维·开发语言·人工智能·功能测试·appium·自动化·测试用例
杜子不疼.7 小时前
【C++ AI 大模型接入 SDK】 - DeepSeek 模型接入(上)
开发语言·c++·chatgpt
加号37 小时前
【C#】 串口通信技术深度解析及实现
开发语言·c#
sycmancia8 小时前
Qt——编辑交互功能的实现
开发语言·qt
石山代码8 小时前
C++ 内存分区 堆区
java·开发语言·c++
无风听海9 小时前
C# 隐式转换深度解析
java·开发语言·c#
一只大袋鼠9 小时前
Git 进阶(二):分支管理、暂存栈、远程仓库与多人协作
java·开发语言·git
LuminousCPP10 小时前
数据结构 - 线性表第四篇:C 语言通讯录优化升级全记录(踩坑 + 思考)
c语言·开发语言·数据结构·经验分享·笔记·学习
web3.088899910 小时前
1688 图搜接口(item_search_img / 拍立淘) 接入方法
开发语言·python