Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
chih98 committed Apr 20, 2017
0 parents commit dedf782
Show file tree
Hide file tree
Showing 8 changed files with 447 additions and 0 deletions.
259 changes: 259 additions & 0 deletions Marko Crnkovic.playground/Contents.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,259 @@
//: That's music to my ears.
//: It's time to make music, and art from prose. How? With a little help from a very special field called mathamagic!

import UIKit
import PlaygroundSupport
import AudioToolbox


// =====================================


// IF ON macOS MAKE SURE ASSISTANT EDITOR IS OPEN


// =====================================

// Choose from what text you want the magic to grow from by commenting and uncommenting a line of code. You can add your own txt file!

// let fileName = "Apple-Event"

let fileName = "Hamlet"

//let fileName = "Lorem-Ipsum"

/* It is cool how a different "language" sounds so differently! */

// let fileName = "/Custom/File/Path"


let fileURL = Bundle.main.url(forResource: fileName, withExtension: "txt")

let file = try String(contentsOf: fileURL!, encoding: String.Encoding.utf8)

let words = Array(file.components(separatedBy: " "))

// Now all the words are seperate objects in an array, and can be worked with!

// Time to create the view and add the text box

let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))

view.backgroundColor = UIColor.gray

let label = UILabel(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height))

label.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
label.shadowColor = #colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1)
label.textAlignment = .center

label.text = words[0]
label.autoresizingMask = [.flexibleTopMargin, .flexibleRightMargin, .flexibleWidth, .flexibleHeight]

view.addSubview(label)




PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = view

// Change Color takes the number and assigns a color to each part of the number. i.e. With 325, red = 0.3, blue = 0.2 and green = 0.5. Alpha is always 1.
func changeColor(_ word: String) -> UIColor {

let score = UInt32(scorer(word))

var r: Float32 = 0
var g: Float32 = 0
var b: Float32 = 0

if score < 10 {

r = Float32(score) / 10
g = Float32(score) / 10
b = Float32(score) / 10

} else if score < 100 {

let scoreWord = String(score)

let firstNumber = Int("\(scoreWord.characters.first!)")

let lastNumber = Int("\(scoreWord.characters.last!)")

r = Float32(firstNumber!) / 10
g = Float32(lastNumber!) / 10
b = Float32(firstNumber!) / 10


} else if score < 1000 {

let scoreWord = String(score)

let firstNumber = Int("\(scoreWord.characters.first!)")

let a = word.index(after: scoreWord.startIndex)
let secondNumber = Int("\(scoreWord[a])")

let thirdNumber = Int("\(scoreWord.characters.last!)")


r = Float32(firstNumber!) / 10
g = Float32(secondNumber!) / 10
b = Float32(thirdNumber!) / 10


} else {

r = 1
g = 1
b = 1

}

return UIColor(colorLiteralRed: Float(r),
green: Float(g),
blue: Float(b),
alpha: 1)

}

// Play tone takes the word, and a time interval, and plays a tone based on the score of the word. Due to the limited range of the tones, if a word is a little high or low in regards to the range, some math is done to rebound the tone back into an audible range. This still leaves the possibility to hear outliers. They will either be a very high pitched or low, almost inaudiable tone.
func playTone(_ word: String, timeInterval: Float) {


// Creating the sequence

var sequence:MusicSequence? = nil
_ = NewMusicSequence(&sequence)

// Making a track

var track:MusicTrack? = nil
var musicTrack = MusicSequenceNewTrack(sequence!, &track)

musicTrack;

// Making note

var tone: UInt8 = 64

let score = Float(scorer(word))

if score < 10 {
let a: Float = score / 10
let b: Float = a * 116
tone = UInt8(b)
} else if score < 100 {
let a: Float = score / 100
let b: Float = a * 116
tone = UInt8(b)
} else if score < 1000 {
let a: Float = score / 1000
let b: Float = a * 116

if b < 45 {

let c = 45 + b
tone = UInt8(c)
} else {
tone = UInt8(b)

}
} else {
tone = 116
}


// Generating time signature and the actual playable note
let time = MusicTimeStamp(timeInterval)

var note = MIDINoteMessage(channel: 0, note: tone, velocity: 255, releaseVelocity: 0, duration: timeInterval)
musicTrack = MusicTrackNewMIDINoteEvent(track!, time, &note)




// Creating the player

var musicPlayer:MusicPlayer? = nil
var player = NewMusicPlayer(&musicPlayer)
player;
player = MusicPlayerSetSequence(musicPlayer!, sequence)
player = MusicPlayerStart(musicPlayer!)


}

// Scorer takes the word including special charactars and then calulates the value of the word based on the length, and ascii values of all characters. Special characters (like commas, and dashes) are included, because if a word is at the end of a clause, it usually is more significant than a word that is in the middle of one.
func scorer(_ word: String) -> UInt32 {
var score: UInt32 = 0
score = UInt32(word.characters.count)

for i in 0...word.characters.count {

// NOTE: endnote 1
score += (String(i).unicodeScalars.filter{$0.isASCII}.first?.value)!

}

return score
}


// Here is where all the fun happens! Counter is the running index, whilie this first if clause is to determine the initial duration of the loop. Then in the loop, all the above functions are called and it calculates everything for the next iteration.
var counter = 0

let scoree = scorer(words[counter])

var timeInterval: Float = 0.5

if scoree < 10 {
timeInterval = Float(scoree) / Float(10)
} else if scoree < 100 {
timeInterval = Float(scoree) / Float(100)
} else if scoree < 1000 {
timeInterval = Float(scoree) / Float(1000)
}

let time = Timer.scheduledTimer(withTimeInterval: TimeInterval(timeInterval), repeats: true) { (time) in

let score = scorer(words[counter + 1])

if score < 10 {
timeInterval = Float(score) / Float(10)
} else if score < 100 {
timeInterval = Float(score) / Float(100)
} else if score < 1000 {
timeInterval = Float(score) / Float(1000)
}



let word = words[counter]
label.text = word
counter += 1

let bg = changeColor(word)

playTone(word, timeInterval: timeInterval)

UIView.animate(withDuration: TimeInterval(timeInterval), delay: 0, options: .allowAnimatedContent, animations: {
view.backgroundColor = bg
}, completion: nil)

if counter == words.count {
time.invalidate()
}
}


/* ------- ENDNOTES --------
As with any academical paper, credit should be given where credit is due.
1. http://stackoverflow.com/questions/29835242/whats-the-simplest-way-to-convert-from-a-single-character-string-to-an-ascii-va
*/

28 changes: 28 additions & 0 deletions Marko Crnkovic.playground/Resources/Apple-Event.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
Good morning. Good morning. Thank you. Thank you. Good morning.
Thank you for joining us and welcome to San Francisco. I’m so glad James got me here on time. It was so much fun seeing he and Farrell, I may have lost my voice.
Apple Music
As you may know, we are working with Carpool Karaoke on some new episodes that will be premiering on Apple Music early next year. So check them out. I can guarantee you everybody singing will have a voice much better than mine.
We’ve got some great things to share with you this morning, and I’d like to get started with a few updates, beginning with Apple Music. As you know, we’ve always had a deep love for music. It inspires us and it’s such a key part of our product experience. Since launch, Apple Music has grown to over 17 million subscribers. Thank you. Our users love having access to over 30 million songs and personal recommendations from people who really know and love music.
There is a great new simple and intuitive design in iOS 10 that makes it so easy to listen to your favorite songs and discover new music. And Apple Music has content that no one else has. Apple Music has become the premier destination for new artists and artists and existing artists to launch their exclusive music.
This past year alone, Apple Music was the first place to hear over 70 great releases from such stars as Taylor Swift, Blake Shelton, Drake, Frank Ocean and so many more. Thank you.
One of our most popular exclusives of all is the Apple Music Festival in London and it begins in just 11 days from now. The spree of that has become a great tradition that our customers look forward to every year. This year we’re celebrating the 10th anniversary of the Apple Music Festival and we had an amazing lineup. This year it includes Elton John, One Republic, Robbie Williams, Britney Spears and so many more great artists. It’s going to be amazing. Now if you can’t make it to London, you can join us and join the millions that will be watching it for free on the livestream from your Apple devices, including your Apple TV. That’s a brief update on Apple Music. It just keeps getting better. Thank you.

App Store
Now I’d like to talk about the App Store. Apps continue to do more and more amazing things from allowing you to rent that spare bedroom to contributing to advanced medical research. The App Store has forever changed the world of software and forever changed all of our lives. And the momentum for apps in the App Store have never been greater. Over 140 billion apps have now been downloaded from the App Store. This is phenomenal.
And what’s even more phenomenal is we continue to set new record and the growth is literally off the charts. In fact, in the last two months, we’ve seen growth rates of over 100% year on year. This is unbelievable. It’s pretty clear from this that our users’ love affair with apps for their iPhone and iPad is as strong as ever.


Now the most recent quarter, the App Store generated twice the global revenue of our nearest competitor. This has been — this is really great for developers, and it’s why that so many developers develop first on iOS and many only on iOS. And this of course is great for our users.
The combination of our incredible products and the success of the App Store has made the iPhone and the iPad the most popular gaming devices in the world. And gaming is the biggest and most popular category on the store with over 0.5 million games to choose from. But there has been something, or rather someone missing. And I’m so happy to announce today he is coming to the App Store.
Welcome Mario, and please welcome for Nintendo, the father of Mario, Shigeru Miyamoto.
Shigeru Miyamoto – Creator of Mario, Nintendo
Hello! Good morning everyone. Thank you, Tim. For the past 30 years, every time Mario has encountered a new platform, he has evolved and continued running towards a new goal. And now Mario is running towards his next goal: iPhone. Please, let me speak in Japanese, so I would ask [Gridiron] to translate.
We want as many people as possible all around the world to be able to enjoy playing as Mario, and they’ll be doing it first on iOS. And they’ll be doing it in a brand new game Super Mario Run.
The magic of Mario is that anyone can pick up a game and instantly start playing. And this time we’ve made it even simpler to begin. So why don’t we show you now?
READ ALSO:   What's Wrong With Your Pa$$W0rd by Lorrie Faith Cranor (Transcript)
Now as the title suggests Mario runs automatically to the right and as he does, he’ll hurdle small gaps and certain enemies. It’s very simple and the movement feels great. With just a tap of the finger anywhere on the touchscreen you can make Mario jump, and the longer you tap, the higher he jumps. This is key to getting high scores. In later levels, you will see blocks that will change Mario’s direction and others that will start and stop him with precision timing. But the goal remains simple: collect as many coins as you can and get to the flagpole at the end of the level before time runs out.
But what’s new this time and what’s different is that you can play the game one handed for the very first time. And what that means is that you can play while holding on to a handle on the subway, or while eating a hamburger, or while eating an apple.
But in addition to the traditional Mario gameplay, we’ve also prepared a brand new way to play. It’s a new battle called Toad Rally. And the first thing that you do in battle mode is you choose an opponent from this list to try to beat their high score. Today I’ve asked [Hidak Ikono] to play for me, so who should he compete against? Looks like he picked Phil!
So we’re going to try to beat Phil’s highest score. Now battle mode will have you competing not only against your friends but for the first time players around the world. And victory in battle mode is determined based on the number of coins you collect and the number of toads you impress, because the toad characters appear every time you do a daring move. And there’s no flagpole in the battle mode. So you just keep running, jumping and collecting coins until time runs out. As you do, you may see a little sticker of Mario moving through the course. In this case, that shows us what Phil was doing on his run where he collected his coins and where he gathered his toad fans. In the matches that you win, the toads you gather will become residents of your very own Mushroom kingdom.
So another new element you can enjoy is expanding and customizing your Mushroom kingdom using the coins you collect in the game. At the end of Battle Mode, Toadette appears to tell you the score and so who won. Sorry, sorry Phil.
We want as many people of all ages to be able to enjoy playing Super Mario Run. And for that reason, we plan on releasing the game at a set price, so you won’t have to worry about continuing to pay. You will just be able to play to your heart’s content.
Loading

0 comments on commit dedf782

Please sign in to comment.