After ios4, audio can be played in the background. You can play the audio in the background in the following two steps.
1. In info. plist, add the "Required background Modes" key and set its value to "app plays audio"
2. Add the following two pieces of code (the premise is that the avfoundation framework has been added) to the Code where the player plays music ):
// Add the background playback code:
AVAudioSession
*session = [
AVAudioSession
sharedInstance
];
[session
setActive
:
YES
error
:nil
];
[session
setCategory
:
AVAudioSessionCategoryPlayback
error
:nil
];
// And set the app to support remote control Event code. Set the app to support remote control events,
// In fact, the app icon is displayed in the dock and the app is opened when you click the image.
// When you lock the screen, double-click the Home key and the playback control button of the application appears on the top of the screen.
[[
UIApplication
sharedApplication
]
beginReceivingRemoteControlEvents
];
// Use the following code to play music and test background playback
// Create a player
AVAudioPlayer
*player = [[
AVAudioPlayer
alloc
]
initWithContentsOfURL
:url
error
:nil
];
[url
release
];
[player
prepareToPlay
];
[player
setVolume
:
1
];
player
.numberOfLoops
= -
1
;
// Set the number of times the music is played-1 to keep repeating
[player
play
];
// Play