Recently prepared to convert the project into OC and Swift Hybrid development, try to write a swift music player demo, realize the advantages of swift relative OC, Nonsense said, first on:
PS: As Jay Iron powder, the theme of the demo must be related to Jay, haha! And I feel like I have the talent to transform the UI, is there wood?
First, import OC file
After you create a swift project, import the OC tool class file and Xcode automatically generates the bridging file
Open this file, at the beginning of importing the OC Tool class header file, you can call the OC tool class
//// Usefileto import your target‘stoto"UIView+Frame.h"
second, interface drawing
Here for convenience, without considering performance issues, just a simple demo, so directly create 10 music buttons, plus a play button and a pause button. The 10 song buttons are placed on top of a uiscrollview. And the music that plays is local music, first create the global variable before viewdidload, the code is as follows:
var Btnindex = 0 let Arrmusicname = [ "Dandelion's convention" , "Stealing Love" , " back ", " advertising balloon ", " Sunshine Otaku ", "Sweet" , "Rainbow" , "Heart Rain" , Span class= "hljs-string" > "Where are You" , "well-being" ] Let Btnplay:uibutton = UIButton (type :. system ) let Btnpause:uibutton = UIButton (type :. system ) override func viewdidload () {
The interface drawing code is as follows:
Let Screen_w = UIScreen. Mainscreen(). Bounds. Size. WidthLet Screen_h = UIScreen. Mainscreen(). Bounds. Size. HeightLet Ivback:uiimageview = Uiimageview (Frame:cgrect (x:0,y: -, Width:screen_w, Height:screen_h)) Ivback. Image= UIImage (named:"Aa.jpg") Self. View. Addsubview(ivback) Let Lbtitle:uilabel = UILabel (Frame:cgrect (x:0,y: -, Width:screen_w, Height: -)) Lbtitle. Text="Lxy's Jay Love Song"Lbtitle. TextColor= Uicolor. Whitecolor() Lbtitle. TextAlignment= Nstextalignment. CenterLbtitle. BackgroundColor= Uicolor. Blackcolor() Lbtitle. Alpha=0.2Self. View. Addsubview(lbtitle) Let Scv:uiscrollview = Uiscrollview (Frame:cgrect (x:0,y: -, Width:screen_w, Height:screen_h- About- -)) SCV. BackgroundColor= Uicolor. Clearcolor() Self. View. Addsubview(SCV) var boom:int =0ForSt inchArrmusicname {print (St) if Let index = Arrmusicname. IndexOf(St) {Let Btn:uibutton = UIButton (type:. System) btn. BackgroundColor= Uicolor. Whitecolor() btn. Alpha=0.5Btn. Settitle(St, Forstate:uicontrolstate. Normal) btn. Settitlecolor(Uicolor. Blackcolor(), Forstate:uicontrolstate. Normal) btn. Titlelabel?. Font= Uifont. Systemfontofsize( -) btn. Layer. Maskstobounds= True BTN. Layer. Shadowoffset= Cgsizemake (0,Ten) btn. Layer. Shadowcolor= Uicolor. Graycolor(). CgcolorBtn. Layer. Shadowopacity=1Btn. Layer. Shadowradius=TenBtn. Layer. Cornerradius=6Btn. Tag= index//Pass the Touch object (that is, the button clicked), you need to define the action parameter, the method name is followed by a colon btn. AddTarget(Self, Action:#selector (Play (_:)), forControlEvents:. Touchupinside)If index%2==0{BTN. Frame= CGRectMake (screen_w/9, -+ (screen_w/3+ screen_w/9) *cgfloat (index/2), screen_w/3, screen_w/3)}else {BTN. Frame= CGRectMake (5*screen_w/9, -+ (screen_w/3+ screen_w/9) *cgfloat (index/2), screen_w/3, screen_w/3)} SCV. Addsubview(btn) boom = Int (btn. Bottom)}} The SCV. Contentsize= Cgsizemake (Screen_w,cgfloat (Boom + -)) Btnplay. Frame= CGRectMake (0, SCV. Bottom, screen_w/2-Ten, -) Btnplay. BackgroundColor= Uicolor. Whitecolor() Btnplay. Alpha=0.5Btnplay. Settitle("Play", Forstate:uicontrolstate. Normal) Btnplay. Settitlecolor(Uicolor. Bluecolor(), Forstate:uicontrolstate. Normal) Btnplay. Titlelabel?. Font= Uifont. Systemfontofsize( -) Btnplay. AddTarget(Self, Action:#selector (Mpmediaplayback.play), forcontrolevents:. Touchupinside)Btnplay. Hidden= True Self. View. Addsubview(Btnplay) Btnpause. Frame= CGRectMake (Ten+ screen_w/2, SCV. Bottom, screen_w/2-Ten, -) Btnpause. BackgroundColor= Uicolor. Whitecolor() Btnpause. Alpha=0.5Btnpause. Settitle("Pause", Forstate:uicontrolstate. Normal) Btnpause. Settitlecolor(Uicolor. Bluecolor(), Forstate:uicontrolstate. Normal) Btnpause. Titlelabel?. Font= Uifont. Systemfontofsize( -) Btnpause. AddTarget(Self, Action:#selector (Mpmediaplayback.pause), forcontrolevents:. Touchupinside)Btnpause. Hidden= True Self. View. Addsubview(Btnpause)} Func Play (Btn:uibutton) {Btnindex = btn. TagLet music = arrmusicname[btn. Tag] Let Path = NSBundle. Mainbundle(). Pathforresource(Music, OfType:"MP3") let Pathurl=nsurl (fileurlwithpath:path!) do {Audioplayer = try Avaudioplayer (contentsofurl:pathurl)} catch {Audioplayer = Nil } Audioplayer?. Preparetoplay() Audioplayer. Play() Btnpause. Hidden= False Btnplay. Hidden= False
Third, music player creation
class AudioManager: NSObject, AVAudioPlayerDelegate { static let sharedManager = AudioManager() // singleton var audioPlayer: AVAudioPlayer!}
Then instantiate the player in the Quju opera variable.
var audioPlayer = AudioManager.sharedManager.audioPlayer
Four, button event binding
1. Music Button plays music event
func playWitnIndex(index: Int){ let music = arrMusicName[index] let"mp3") let pathURL=NSURL(fileURLWithPath: path!) do { try AVAudioPlayer(contentsOfURL: pathURL) catch { audioPlayer = nil } audioPlayer?.prepareToPlay() audioPlayer.play() false false }
This way, button to bring it over, by the tag value of button to determine the buttons clicked
2. Click event for Play button
play(){ audioPlayer.play() }
3. Pause button Click event
pause(){ audioPlayer.pause() }
Here, the basic function of the music player has been realized, the click will have music playback, and the play pause function has been implemented
The realization of music backstage playing
To achieve the background music playback function, but also learn to set the music player
Add the code in the Viewdidload method:
UIApplication.sharedApplication().beginReceivingRemoteControlEvents() do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord) try AVAudioSession.sharedInstance().setActive(true) } catch { }
Just adding this is not enough, you need to set up the project
Add required background modes in Info.plist, specifically
In this way, the music player realizes the background play function
Six, music player lock screen music playback settings
Add the Setlockview method with the following code:
Func Setlockview () {Mpnowplayinginfocenter. Defaultcenter (). Nowplayinginfo = [//Song nameMpmediaitempropertytitle: Arrmusicname[Btnindex],//Singermpmediaitempropertyartist:"Jay Chou" ,//Lock screen Picturempmediaitempropertyartwork: Mpmediaitemartwork(Image: UIImage(named: "Aa.jpg")!),// mpnowplayinginfopropertyplaybackrate:1.0,//Total length of timempmediaitempropertyplaybackduration: Audioplayer. Duration,//Current timeMpnowplayinginfopropertyelapsedplaybacktime: Audioplayer. CurrentTime]}
Call this method in the Viewdidload method:
self.setLockView()
This enables the Lock screen interface button settings
Vii. solutions to the problem of the speaker
At this point, although the functionality is implemented, you will find that the music plays a particularly small sound because the Avaudioplayer default is the handset playback, not the speaker playback
Here you need to add the following setup code in the player settings
let session = AVAudioSession.sharedInstance() try session.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: AVAudioSessionCategoryOptions.DefaultToSpeaker)
Other settings:
Here, the swift version of the lxy Jay Love Song app is done, the article finally attached to the project source (because the music file is too large, only the first two songs), I hope you like:
Project Source
Swift Music player Project-"Lxy's Jay Love Song" Development Practical Walkthrough