In my viewcontroller.h file I have:
- (void)startBackgroundMusic;
- (void)stopBackgroundMusic;
#property (strong, nonatomic) AVAudioPlayer *audioPlayer;
In my viewcontroller.m I have:
- (void)startBackgroundMusic
{
NSError *err;
NSURL *file = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#" DK" ofType:#"mp3"]];
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:&err];
if (err) {
NSLog(#"error in audio play %#",[err userInfo]);
return;
}
[_audioPlayer prepareToPlay];
_audioPlayer.numberOfLoops = -1;
[_audioPlayer setVolume:.5];
[_audioPlayer play];
}
- (void) stopBackgroundMusic {
[_audioPlayer pause];
}
In my MyScene.m file when I click a switch I have off I run:
[vc stopBackgroundMusic];
and I also have:
ViewController *vc;
declared above with viewcontroller.h imported.
This doesn't work. It plays fine but I just can't stop it. It seems easy to accomplish but maybe I'm missing something.
Related
Hi I am trying to play an audio file, but it doesn't work for some reason. I dont get any errors so i assume it must work but my audio doesn't play can u help me pls
NSString *path = #"%#/Elevator.mp3";
NSString *soundFilePath = [NSString stringWithFormat:path,[[NSBundle mainBundle] resourcePath]];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSLog(soundFilePath);
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = 1; //Infinite
[player play];
I do have this line constantly in my console
skipping input stream 0 0 0x0
Try creating class attribute for a player:
#property (nonatomic, strong) AVAudioPlayer *player;
And then use it to play sound. Otherwise, your player will be deallocated right after the method where it was created finishes executing.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:yourUrlString]];
NSURLSession *session = [NSURLSession sharedSession];
task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (data) {
[self performSelectorOnMainThread:#selector(upadateCurrentTrack:) withObject:data waitUntilDone:NO];
}
}];
[task resume];
-(void)upadateCurrentTrack:(NSData *)data {
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:NULL];
audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
[audioPlayer play];
}
I created sample one for your question.It plays audio successfully now.
I forgot to say this.First set
ViewController.h
#import <UIKit/UIKit.h>
#import <AVKit/AVKit.h> //For AVPlayerViewController
#import <AVFoundation/AVFoundation.h> //For AVAudioPlayer
#interface ViewController : UIViewController
#property (nonatomic,strong)AVAudioPlayer *player;
- (IBAction)actionPlayAudio:(id)sender;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize player;
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)actionPlayAudio:(id)sender
{
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"Elevator" ofType:#"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
[player play];
}
#end
I have the following code in my viewcontroller. When I run, the audio doesn't play in the xcode simulator. Any advice on what I should do?
Also, I've saved anomaly.mp3 in the same directory (no sub-folders) as ViewController.m.
#import <AVFoundation/AVFoundation.h> //before viewDidLoad
NSError * error = nil;
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"anomaly"
ofType:#"mp3"]];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error){
NSLog(#"error: %#", [error localizedDescription]);
}
NSLog(#"test");
[audioPlayer play];
Try setting the audio player's volume. You can also check the results of the "play" function, to see if things worked correctly. The play function implicitly calls prepareToPlay. This function can fail out for a number of reasons, irritatingly without any error object or message...
NSError * error = nil;
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"anomaly"
ofType:#"mp3"]];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error){
NSLog(#"error: %#", [error localizedDescription]);
} else {
audioPlayer.volume = 50;
if([audioPlayer play]) NSLog(#"Should be playing");
else NSLog(#"Something weird happened"); //usually related to unavailable hardware
}
Keep a strong reference to the audioPlayer by declaring it as:
#property (nonatomic) AVAudioPlayer *audioPlayer;
and then use self.audioPlayer wherever you have used audioPlayer.
The problem with your code is that because your audioPlayer is just a local variable to the method, it gets deallocated by ARC as soon as your method is completed. Keeping a strong reference to it will keep the audioPlayer object and memory and your sound will keep playing as long as you don't call
[self.audioPlayer stop];
For some reason, the cleanupPlayer method is a little buggy and isn't releasing the audio player correctly. My application crashes from time to time, and I suspect it's due to a memory issue. Also, when I try to play an audio file twice (on button click), the second time the audio sometimes cuts out. I'm a bit of a newbie, so any help would be greatly appreciated!
Here is a snippet of code:
.h file:
#property (retain,nonatomic)AVAudioPlayer *player;
.m file:
-(void)playSound:(NSString *)fileName
{
// Play
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:fileName ofType:kSoundFileType]];
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
_player.delegate = self;
[_player prepareToPlay];
[_player play];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
[self cleanupPlayer];
}
-(void)cleanupPlayer
{
if(_player != nil) {
[_player release];
}
try this...
-(void)playSound:(NSString *)fileName
{
if (_player.isPlaying) {
[_player stop];
}
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:fileName ofType:#"mp3"]];
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
_player.delegate = self;
[_player prepareToPlay];
[_player play];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
[self cleanupPlayer];
}
-(void)cleanupPlayer
{
_player =nil;
}
I'm following in a tutorial on how to play mp3 sounds when pressing a button.
I created a button (playSound).
I added it to the view controller interface:
- (IBACTION)playSound:(id)sender;
in the implementation I declared the needed header files and I wrote the following:
#import "AudioToolbox/AudioToolbox.h"
#import "AVFoundation/AVfoundation.h"
- (IBAction)playSound:(id)sender {
//NSLog(#"this button works");
AVAudioPlayer *audioPlayer;
NSString *audioPath = [[NSBundle mainBundle] pathForResource:#"audio" ofType:#"mp3"];
//NSLog(#"%#", audioPath);
NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
//NSLog(#"%#", audioURL);
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:nil];
[audioPlayer play];
}
I'm not getting any errors. the NSlogs are logging the URL fine, and now I have no clue where to look further. I also checked if my MP3 sound was maybe damaged, but that was also not the case. all i hear is a little crackling noise for 1 second. then it stops.
You declared a local variable audioPlayer to hold a pointer to the player. As soon as your button handler returns the player is being released before it has a chance to play your sound file. Declare a property and use it instead of the local variable.
In YourViewController.m file
#interface YourViewController ()
#property (nonatomic, strong) AVAudioPlayer *audioPlayer;
#end
or in YourViewController.h file
#interface YourViewController : UIViewController
#property (nonatomic, strong) AVAudioPlayer *audioPlayer;
#end
Then replace audioPlayer with self.audioPlayer in your code.
try this its working for me
in .h
AVAudioPlayer * _backgroundMusicPlayer;
in .m
NSString *backgroundMusicPath = [[NSBundle mainBundle] pathForResource:#"Theme" ofType:#"mp3"];
NSURL *backgroundMusicURL = [NSURL fileURLWithPath:backgroundMusicPath];
NSError *error;
_backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:&error];
[_backgroundMusicPlayer setDelegate:self]; // We need this so we can restart after interruptions
[_backgroundMusicPlayer setNumberOfLoops:-1];
[_backgroundMusicPlayer play];
Edited
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"Name of your audio file"
ofType:#"type of your audio file example: mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
audioPlayer.numberOfLoops = -1;
audioPlayer.delegate=self;
[audioPlayer play];
Try this and let me know. Make sure you set the delegate for audioPlayer.
Firstly re add your music file in your project , then try this code
With the log you can see error.
NSError *error;
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"bg_sound" ofType:#"mp3"]];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error){
//Print Error
NSLog(#"Error in audioPlayer: %#",
[error localizedDescription]);
} else {
audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
[audioPlayer setNumberOfLoops: -1];
[audioPlayer play];
audioPlayer.volume=1.0;
}
Make sure your music files are properly added in project
I have a very simple app that is supposed to only play an audio file on view. Instead my Xcode is crashing.
I am using Xcode version 6. I have implemented the AVFoundation Framework
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *audioPath = [[NSBundle mainBundle] pathForResource:#"Crowd_cheering"
ofType:#"m4a" ];
NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
NSError *error;
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];
[self.player play];
}
//Try like this with error condition:
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"Moderato"
ofType:#"mp3"]];
NSError *error;
_audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error)
{
NSLog(#"Error in audioPlayer: %#",
[error localizedDescription]);
} else {
_audioPlayer.delegate = self;
[_audioPlayer prepareToPlay];
}
//Before that add import AVFoundation/AVFoundation.h and add delegate AVAudioPlayerDelegate
//then Implement the AVAudioPlayerDelegate Protocol Methods like this
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
}
-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
}
-(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player
{
}
-(void)audioPlayerEndInterruption:(AVAudioPlayer *)player
{
}
Make sure u connected ur play button properly or not and also check whether you Added an Audio File to the Project Resources properly.