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

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

相关推荐
爱分享的程序员3 分钟前
前端跨端框架的开发以及IOS和安卓的开发流程和打包上架的详细流程
android·前端·ios
努力学习的小廉11 分钟前
【C++】 —— 笔试刷题day_21
开发语言·c++·算法
kadog13 分钟前
《Python3网络爬虫开发实战(第二版)》配套案例 spa6
开发语言·javascript·爬虫·python
徒慕风流14 分钟前
利用Python爬虫实现百度图片搜索的PNG图片下载
开发语言·爬虫·python
钢铁男儿33 分钟前
C# 实战_RichTextBox选中某一行条目高亮,离开恢复
开发语言·c#
Macle_Chen34 分钟前
ios开发中xxx.debug.dylib not found
ios·bug·debug.dylib
依旧阳光的老码农1 小时前
Windows下使用 VS Code + g++ 开发 Qt GUI 项目的完整指南
开发语言·windows·qt
等什么君!1 小时前
SpringMVC处理请求映射路径和接收参数
java·开发语言·spring
曹牧1 小时前
Java:XML被自动转义
xml·java·开发语言
愚润求学1 小时前
【专题刷题】二分查找(一):深度解刨二分思想和二分模板
开发语言·c++·笔记·leetcode·刷题