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

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

相关推荐
Reese_Cool9 分钟前
【C语言二级考试】循环结构设计
android·java·c语言·开发语言
海里真的有鱼10 分钟前
Spring Boot 项目中整合 RabbitMQ,使用死信队列(Dead Letter Exchange, DLX)实现延迟队列功能
开发语言·后端·rabbitmq
zxctsclrjjjcph26 分钟前
【C语言】常见的C语言概念
c语言·开发语言
小灰灰爱代码31 分钟前
C++——求3个数中最大的数(分别考虑整数、双精度数、长整数的情况),用函数模板来实现。
开发语言·c++·算法
Eiceblue37 分钟前
Python 复制Excel 中的行、列、单元格
开发语言·python·excel
项目題供诗41 分钟前
尚品汇-秒杀商品存入缓存、Redis发布订阅实现状态位(五十一)
开发语言·php
m0_714590261 小时前
汇编(实现C语言程序的调用)
c语言·开发语言·汇编
做技术的Pandaer1 小时前
Go 第二期
开发语言·golang
新知图书1 小时前
Rust编程的作用域与所有权
开发语言·后端·rust
极客代码1 小时前
OpenCV Python 深度指南
开发语言·人工智能·python·opencv·计算机视觉