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

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

相关推荐
Joey_friends26 分钟前
【Linux】线程详解
开发语言
_GR31 分钟前
Qt开发⑧Qt的窗口_下_浮动窗口+对话框
开发语言·css·c++·qt·microsoft
北京自在科技37 分钟前
苹果折叠屏iPhone突破折痕难题 或将在2026年发布
ios·iphone·findmy·折叠屏·库克
一粒沙-37 分钟前
iOS 将GIF图分享至微信
前端·ios
Good Note39 分钟前
Golang——常用库context和runtime
开发语言·爬虫·golang
清河__1 小时前
【Go】十七、grpc 服务的具体功能编写
开发语言·后端·golang
张声录11 小时前
国密算法Sm2工具类--golang实现版
开发语言·后端·golang
HH牛码2 小时前
C# 中 Array、ArrayList 和 List 的比较
开发语言·c#
zr想努力3 小时前
Lua的table类型的增删改查操作
java·开发语言·lua
Evand J4 小时前
【MATLAB代码】RSA加密和解密例程
开发语言·算法·matlab