开发者

Sound does not play while using AVAudioPlayer

开发者 https://www.devze.com 2023-03-25 00:10 出处:网络
Here is my code on button click - (void)playButton:(id)sender { NSLog(@\"PlayButton Clicked!!!...\"); audioPlayer = [self setUpAudioPl开发者_C百科ayer:[songs objectAtIndex:i]];

Here is my code on button click

- (void)playButton:(id)sender
{
    NSLog(@"Play  Button Clicked!!!...");
    audioPlayer = [self setUpAudioPl开发者_C百科ayer:[songs objectAtIndex:i]];
}

-(AVAudioPlayer *)setUpAudioPlayer:(NSString *)filename
{
    NSLog(@"File name : %@",filename);

    NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:@"caf"]; 

    NSLog(@"File path = %@",path);

    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil]; 

    //audioPlayer.volume = 0.5;
    [audioPlayer prepareToPlay];
    [audioPlayer play];
    NSLog(@"Song is playing....");

    return [audioPlayer autorelease];
}

here songs is NSMutableArray which contains file name... All things go correct with NSLog... But no sound is coming and no error comes.. What is wrong with the code..???


Your audio player is probably getting released as soon as it starts playing. Try to retain it after setUpAudioPlayer is called.


Most probably you need to initialize an audio session, some like this

- (void)setupAudioSession
{

    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *error = nil;

    [session setCategory: AVAudioSessionCategoryPlayback error: &error];
    if (error != nil)
        NSLog(@"Failed to set category on AVAudioSession");

    // AudioSession and AVAudioSession calls can be used interchangeably
    OSStatus result = AudioSessionAddPropertyListener(kAudioSessionProperty_AudioRouteChange, RouteChangeListener, self);
    if (result) NSLog(@"Could not add property listener! %d\n", result);

    BOOL active = [session setActive: YES error: nil];
    if (!active)
        NSLog(@"Failed to set category on AVAudioSession");


}
0

精彩评论

暂无评论...
验证码 换一张
取 消