[IOS development-118] AVFoundation framework: AudioServices... sound effects, AVAudioPlayer music, AVAudioRecord recording,

Source: Internet
Author: User

[IOS development-118] AVFoundation framework: AudioServices... sound effects, AVAudioPlayer music, AVAudioRecord recording,

(1) sound playback: the Core code mainly creates a player and then plays the video.

# Import "WPSound. h "# import <AVFoundation/AVFoundation. h> @ implementation WPSoundstatic NSMutableDictionary * _ soundIDDict; + (void) initialize {_ soundIDDict = [NSMutableDictionary dictionary];} // cannot be loaded with laziness, because of the time class method used by the user, you need to set/-(NSMutableDictionary *) soundIDDict {// if (_ soundIDDict = nil) in the class initialization above) {// _ soundIDDict = [NSMutableDictionary dictionary]; //} // return _ soundIDDict; //} + (void) soundPlay :( NSString *) fileN Ame {if (! FileName) return; // retrieve soundID SystemSoundID soundID = [_ soundIDDict [fileName] unsignedIntValue]; if (! SoundID) {NSURL * url = [[NSBundle mainBundle] URLForResource: fileName withExtension: nil]; if (! Url) return; encode (_ bridge CFURLRef) url, & soundID); // put it into the dictionary _ soundIDDict [fileName] =@ (soundID);} AudioServicesPlaySystemSound (soundID );} + (void) soundDispose :( NSString *) fileName {if (fileName) return; SystemSoundID soundID = [_ soundIDDict [fileName] unsignedIntValue]; if (! SoundID) return; AudioServicesDisposeSystemSoundID (soundID); // remove [_ soundIDDict removeObjectForKey: fileName] from the dictionary;} @ end


(2) music playback and core code. Note that the created player must be a global variable.

# Import "MusicTool. h "@ implementation MusicToolstatic NSMutableDictionary * _ audioPlayerDict; static AVAudioPlayer * _ audioPlayer; + (void) initialize {_ audioPlayerDict = [NSMutableDictionary dictionary]; // set the session type AVAudioSession * session = [AVAudioSession sharedInstance]; [session setCategory: AVAudioSessionCategorySoloAmbient error: nil]; [session setActive: YES error: nil];} + (AVAudioPlayer *) musicPlay :( NSString *) FileName {if (! FileName) return nil; // retrieve the player AVAudioPlayer * audioPlayer = _ audioPlayerDict [fileName]; if (! AudioPlayer) {NSURL * url = [[NSBundle mainBundle] URLForResource: fileName withExtension: nil]; if (! Url) return nil; // create audioPlayer AVAudioPlayer * audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: url error: NULL]; _ audioPlayer = audioPlayer; [_ audioPlayer prepareToPlay]; _ audioPlayer. enableRate = YES; // set the playing speed below. You can test the playback speed with // _ audioPlayer. rate = 10; // _ audioPlayerDict [fileName] = audioPlayer;} if (! _ AudioPlayer. isPlaying) {[_ audioPlayer play];} return _ audioPlayer;} + (void) musicPause :( NSString *) fileName {if (! FileName) return; AVAudioPlayer * audioPlayer = _ audioPlayerDict [fileName]; if (audioPlayer. isPlaying) {[audioPlayer pause] ;}+ (void) musicStop :( NSString *) fileName {if (! FileName) return; AVAudioPlayer * audioPlayer = _ audioPlayerDict [fileName]; if (audioPlayer. isPlaying) {[audioPlayer stop]; [_ audioPlayerDict removeObjectForKey: fileName] ;}+ (AVAudioPlayer *) currentPlayingAudioPlayer {for (NSString * fileName in _ audioPlayerDict) {AVAudioPlayer * audioPlayer = _ audioPlayerDict [fileName]; if (audioPlayer. isPlaying) {return audioPlayer;} return nil;} @ end

(3) Recording and core code.

# Import "ViewController. h "# import <AVFoundation/AVFoundation. h> @ interface ViewController () @ property (nonatomic, strong) AVAudioRecorder * recorder; @ property (nonatomic, strong) CADisplayLink * link; @ property (nonatomic, assign) float silentDuration; -(IBAction) recordStart :( id) sender;-(IBAction) recordStop :( id) sender; @ end @ implementation ViewController-(CADisplayLink *) link {if (_ link = nil) {_ link = [CADisplayLink displayLinkWithTarget: self selector: @ selector (update)];} return _ link;}-(void) update {// update the recorded value [self. recorder updateMeters]; // obtain the average beam float power = [self. recorder averagePowerForChannel: 0]; if (power <-30) {self. silentDuration + = self. link. duration; if (self. silentDuration> = 2) {[self. recorder stop]; [self. link invalidate]; self. link = nil ;}} else {self. silentDuration = 0 ;}}-(void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib .} -(void) didReceiveMemoryWarning {[super didreceivemorywarning]; // Dispose of any resources that can be recreated .} -(IBAction) recordStart :( id) sender {NSString * path = [[NSSearchPathForDirectoriesInDomains (NSDocumentationDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent: @ "test. caf "]; NSURL * url = [NSURL fileURLWithPath: path]; NSMutableDictionary * setting = [NSMutableDictionary dictionary]; // audio format setting [AVFormatIDKey] = @ (kAudioFormatAppleIMA4 ); // audio sampling rate setting [AVSampleRateKey] = @ (8000.0); // number of audio channels setting [AVNumberOfChannelsKey] = @ (1 ); // linear audio bit depth setting [AVLinearPCMBitDepthKey] = @ (8); AVAudioRecorder * recorder = [[AVAudioRecorder alloc] initWithURL: url settings: setting error: nil]; // allow decibel recorder measurement. meteringEnabled = YES; // buffer [recorder prepareToRecord]; // recording [recorder record]; self. recorder = recorder; // enable the timer self. silentDuration = 0; [self. link addToRunLoop: [nsunloop mainRunLoop] forMode: NSDefaultRunLoopMode];}-(IBAction) recordStop :( id) sender {[self. link invalidate]; self. link = nil; [self. recorder stop];} @ end

(3) play music in the background and set three places.

-- Set in AppDelegate. m

- (void)applicationDidEnterBackground:(UIApplication *)application {    [application beginBackgroundTaskWithExpirationHandler:nil];}

-- Set in info. plist


-- Set the audio session type in the Program (which can be omitted)

+ (Void) initialize {_ audioPlayerDict = [NSMutableDictionary dictionary]; // sets the session type AVAudioSession * session = [AVAudioSession sharedInstance]; [session setCategory: callback error: nil]; [session setActive: YES error: nil];}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.