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

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

相关推荐
flysh051 分钟前
深度解析 C# 核心:类(Class)的设计精髓与高级特性
开发语言·c#
Feibo20115 分钟前
R-3east
开发语言·r语言
_OP_CHEN8 分钟前
【从零开始的Qt开发指南】(十四)Qt 窗口之“三剑客”:工具栏、状态栏、浮动窗口进阶实战指南
开发语言·c++·qt·前端开发·gui开发·qt窗口
古城小栈9 分钟前
Rust 模块管理与文件联动
开发语言·后端·rust
会算数的⑨16 分钟前
Java场景化面经分享(一)—— JVM有关
java·开发语言·jvm·后端·面试
葵花楹19 分钟前
【JAVA期末复习】
java·开发语言·排序算法
一叶之秋141223 分钟前
QT常用控件(二)
开发语言·qt
nuowenyadelunwen24 分钟前
Harvard CS50 Week 6 Python
开发语言·python
饼干,26 分钟前
期末考试3
开发语言·人工智能·python
山山而川 潺潺如镜33 分钟前
python防止程序多开,但程序运行脚本
android·开发语言·python