With this simple coding you can play a playlist on your device from your Unity3D Game. Why license royalties when you can get the user to do it for you per individual basis. I am using this in my game Snowboarding+ (see gameplay demo above). If there is no music on your device it'll finally play the local music in your Unity 3D app. This plays the playlist called Snowboarding+
in AppController.mm (also add MediaPlayer.framework):
#include <MediaPlayer/MediaPlayer.h>
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
[self playMusic];
}
- (void) playMusic {
// Instantiate a music player
MPMusicPlayerController *appPlayer = [MPMusicPlayerController applicationMusicPlayer];
// Shuffle all songs
[appPlayer setShuffleMode:MPMusicShuffleModeSongs];
// Assume we will not find our playlist
BOOL playlistFound = NO;
// Get a collection of all playlists on the device
MPMediaQuery *playlistsQuery = [MPMediaQuery playlistsQuery];
NSArray *playlists = [playlistsQuery collections];
NSString *plus;
plus = @"all";
// Check each playlist to see if it is the right one
for (MPMediaPlaylist *playlist in playlists) {
NSString *playlistName = [playlist valueForProperty: MPMediaPlaylistPropertyName];
if ([playlistName isEqualToString:@"Snowboarding+"]) {
// Add the playlist to the player's queue and get out of here
[appPlayer setQueueWithItemCollection:playlist];
playlistFound = YES;
plus = @"snowboarding+";
break;
}
}
// If no playlist found, just play All playlist
if (!playlistFound) {
for (MPMediaPlaylist *playlist in playlists) {
NSString *playlistName = [playlist valueForProperty: MPMediaPlaylistPropertyName];
if ([playlistName isEqualToString:@"All"]) {
// Add the playlist to the player's queue and get out of here
[appPlayer setQueueWithItemCollection:playlist];
playlistFound = YES;
plus = @"all";
break;
}
else
{
//IF NO ALL play a random song
[appPlayer setQueueWithQuery: [MPMediaQuery songsQuery]];
plus = @"random";
}
}
}
// Start playing from the beginning of the queue
[appPlayer play];
if (appPlayer.playbackState == MPMusicPlaybackStatePlaying)
{
UnitySendMessage("Camera", "isPlaying","TRUE");
NSLog(@"%@ is playing",plus);}
else
{
UnitySendMessage("Camera", "isPlaying","FALSE");
NSLog(@"internal music from Unity3D App is playing");}
}
}
In Unity 3D add the following to the Script on your Camera or any game object from above:
var isMusicPlaying: boolean = false;
@script RequireComponent(AudioSource)
function Start() {
// Delay a clip by 10 sec (44100 samples)
#if UNITY_EDITOR || UNITY_ANDROID || UNITY_OSX
audio.Play(44100 * 5);
#endif
}
function isPlaying(message:String)
{
if (message == "TRUE") {isMusicPlaying = true; audio.Stop(); }
if (message == "FALSE") {isMusicPlaying = false; audio.Play(); }
Debug.Log("Is the Music Playing from Device? " + message);
}
No comments:
Post a Comment