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

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

相关推荐
CoderIsArt5 小时前
C#中UI 线程与 Dispatcher
开发语言·ui·c#
AI情绪识别开源8 小时前
检信 ALLEMOTION OS 加密打包可执行程序 — 全面测试报告版本: v1.3功能测试 / 性能测试 /
开发语言·数据结构·人工智能·功能测试
「QT(C++)开发工程师」9 小时前
C++ auto 用法详解
开发语言·c++
OPEN-F9 小时前
C++STL教程:容器适配器与实用工具
开发语言·c++
yaoxin5211239 小时前
507. Java 反射 - 在 BeanFactory 中实现依赖注入
java·开发语言
OPEN-F9 小时前
C++模板教程:变参模板、折叠表达式与SFINAE
java·开发语言·c++
有点。9 小时前
C++二叉搜索树进阶
开发语言·c++
HugoStudio_SWAN9 小时前
【擦除重绘】C++ 控制台动画:弹跳 Logo DVD 屏保效果
开发语言·c++·学习·程序人生
sakiko_11 小时前
Swift学习笔记42-SwiftUI的属性包装器(讲解+面试)
笔记·学习·ios·swiftui·swift