90课:开发一个摇一摇 App

2016-06-03  本文已影响251人  sing_crystal

课程笔记文集地址:Udemy课程:The Complete iOS 9 Developer Course - Build 18 Apps

本节开发一个摇一摇的 App,摇一摇之后就自动随机出现一段小音频。用到的完全是上一节课中学到的摇一摇知识和之前学到的播放音频的知识。

最终效果图如下:

老师推荐了一个网址:http://www.freesfx.co.uk/ 用来下载免费的音频文件,目前可以不用翻墙就能访问,不过速度好慢,需要等待好久才能打开页面,而且必须注册才能下载,我觉得太麻烦,就使用了自己电脑里的几个文件,反正是练习嘛。

一、Storyboard

拖入Label控件,设置字号字体,设置 AutoLayout 约束。

二、写代码

1、创建摇一摇方法

    override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
        if event?.subtype == UIEventSubtype.MotionShake {
            
        }
    }

2、音频播放
(1)
初步设置:把 .mp3 文件直接拖到 Xcode 里,注意勾选 Copy items if needed,如下图:


点击 Finish,然后目录里就有音频啦~

(2)
引入 AVFoundation 框架,在类文件里进行基本设置:


(3)
在摇一摇方法里实现播放的方法:

    override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
        if event?.subtype == UIEventSubtype.MotionShake {
            let audioPath = NSBundle.mainBundle().pathForResource("30-3", ofType: ".mp3")!
            do {
                try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
                player.play()
            } catch {
                print("出现错误")
            }
        }
    }

3、实现随机播放
到目前为止,摇一摇之后能够立即播放音乐了,但是音频还是固定的,如何才能随机播放呢?

初步思路:首先把所有的音频文件名称放入一个数组里,只存名称,数组是String类型,然后用随机函数生成数组的index值,每次摇一摇,就播放随机函数生成的index对应的音频名称。

创建音频名称数组常量:

let audioArray = ["30-3","29-3","30-1","30-2","29-2","28-2","28-3"]

创建随机函数:

let indexNumber = Int(arc4random_uniform(UInt32(audioArray.count)))

在摇一摇播放方法里使用随机方法:

    override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
        if event?.subtype == UIEventSubtype.MotionShake {
            let indexNumber = Int(arc4random_uniform(UInt32(audioArray.count)))
            let audioPath = NSBundle.mainBundle().pathForResource(audioArray[indexNumber], ofType: ".mp3")!
            do {
                try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
                player.play()
            } catch {
                print("出现错误")
            }
        }
    }

到此结束了。

上一篇下一篇

猜你喜欢

热点阅读